Start free

Expert · Parsing · 255 of 264

Tidy a path

Simplify a Unix-style path: . means the current folder, .. goes one folder up (but not above /), and repeated slashes count as one. The result starts with / and has no slash at the end (except for the root /).

Input: an absolute path. Output: the simplified path.

Examples

Input
/home/
Output
/home
Input
/../
Output
/
Input
/home//foo/
Output
/home/foo
Input
/a/./b/../../c/
Output
/c

One more test checks other inputs when you press Check.

Stuck? The idea behind parsing

Turning text into structure: read it piece by piece (tokens: numbers, operators, brackets), then work out what they mean, in order.

A stack keeps what is waiting, such as an operator until both its numbers are known.

tokens = "3 4 + 2 *".split()
stack = []
for t in tokens:
    if t in "+*":
        b, a = stack.pop(), stack.pop()
        stack.append(a + b if t == "+" else a * b)
    else:
        stack.append(int(t))
print(stack[0])  # 14

Watch for: Never run the text with eval(): work it out yourself, so you decide what is allowed.

All the parsing exercises
Your code
Opening the code editor…
Python 3.14 in your browser
Output
Run shows what your program prints. Check tests it on every example and the hidden tests.

More parsing exercises