50 XP

57. Simplify a file path

Intermediate stacks parsing

On Linux and macOS a file path such as /home/ana/docs names folders from the top (/, the root) down. A path can take detours: . means "this folder", .. means "the folder above", and repeated slashes mean nothing extra.

Write a function simplify(path) that takes a path starting with / and returns the shortest path to the same place:

  • It starts with a single /, and its folder names are separated by single slashes.
  • It has no . or .. parts, and no / at the end, except for the root itself, "/".
  • .. at the root stays at the root: there is nothing above it.
  • Any other part is a folder name, even ... or .hidden.

Example 1

Inputpath = "/home//ana/./docs/"
Output"/home/ana/docs"
ExplanationThe extra slash and the "." go.

Example 2

Inputpath = "/a/b/../../c"
Output"/c"
ExplanationDown to a/b, up twice, then into c.

Example 3

Inputpath = "/../"
Output"/"
ExplanationNothing is above the root.

Constraints

  • path has 1 to 200 characters and starts with /.
  • Folder names are made of letters, digits, . and _.

Submit also runs 9 more tests you can't see.

Practises String Methods (lesson 5).

Code
def simplify(path):
    """Write a Unix path in its shortest form.

    path: str, starting with "/"
    Returns: str, the same place with no ".", "..", or
        extra slashes
    """
    # Write your code here
    pass