Drill

ProblemsPython › patterns

Tidy up a file path

hardpatternsStacksStringsParsingPython

A storage service is handed paths with stray slashes and dot segments in them, and stores exactly one canonical form.

tidy_path(raw: string) → string

Solve it in the editor →

Where you start

def tidy_path(raw: str) -> str:
    

Worked examples

CallResult
tidy_path("/home//user/")"/home/user"
tidy_path("/a/./b/../c")"/a/c"
tidy_path("/../")"/"
tidy_path("/")"/"

Hint

Split on the slash and push each real segment onto a stack; ".." pops instead. Joining the stack back up gives the answer.

Reference solution in Python
def tidy_path(raw: str) -> str:
    kept = []
    for part in raw.split("/"):
        if part == "" or part == ".":
            continue
        if part == "..":
            if kept:
                kept.pop()
        else:
            kept.append(part)
    return "/" + "/".join(kept)

The same problem in another language

More patterns problems in Python