easy +8 pts

Pathlib Operations: File Path Basics

Use pathlib to extract name, suffix, parent, and stem from file paths.

Write a function `analyze_path(path_str: str) -> dict` that takes a string representing a file path and returns a dictionary with the following keys: - `name`: the final component of the path (including extension) - `stem`: the name without the suffix - `suffix`: the file extension including the dot (empty string if none) - `parent`: the parent directory as a string (use the parent's string representation) Use `pathlib.Path` from the standard library. The input is relative or absolute; handle paths that use forward slashes (`/`) regardless of the operating system. For the root path `"/"`, treat it as its own parent: the `name` and `stem` should both be `"/"` and `parent` should be `"/"`. **Function signature:** `def analyze_path(path_str: str) -> dict:` **Examples:** ``` >>> analyze_path("/home/user/docs/report.txt") {'name': 'report.txt', 'stem': 'report', 'suffix': '.txt', 'parent': '/home/user/docs'} >>> analyze_path("archive.tar.gz") {'name': 'archive.tar.gz', 'stem': 'archive.tar', 'suffix': '.gz', 'parent': '.'} >>> analyze_path("folder/") {'name': 'folder', 'stem': 'folder', 'suffix': '', 'parent': '.'} >>> analyze_path("/") {'name': '/', 'stem': '/', 'suffix': '', 'parent': '/'} ``` Note: `Path("folder/")` gives name `folder`, parent `.`, etc.

Constraints

Input is a non-empty string containing no null bytes. The path may be absolute or relative, may have multiple levels, and may end with a slash. The function should not raise any exceptions for valid input. Complexity: O(length of path).

Example

>>> analyze_path("/home/user/docs/report.txt")
{'name': 'report.txt', 'stem': 'report', 'suffix': '.txt', 'parent': '/home/user/docs'}
>>> analyze_path("archive.tar.gz")
{'name': 'archive.tar.gz', 'stem': 'archive.tar', 'suffix': '.gz', 'parent': '.'}
>>> analyze_path("folder/")
{'name': 'folder', 'stem': 'folder', 'suffix': '', 'parent': '.'}
>>> analyze_path("/")
{'name': '/', 'stem': '/', 'suffix': '', 'parent': '/'}
8 points ~10 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Create a Path object from the string: `p = Path(path_str)`.
Use `p.name`, `p.stem`, `p.suffix`, and `p.parent` to get each component.
For the root path, `p.name` is '' and `p.parent` is '/', so handle that case manually.
Convert `parent` to string with `str(p.parent)`.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.