57. Simplify a file path
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
path = "/home//ana/./docs/""/home/ana/docs"Example 2
path = "/a/b/../../c""/c"Example 3
path = "/../""/"Constraints
pathhas 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).
path.split("/")breaks the path into its parts. Repeated slashes give empty parts"", which can be skipped like".".- Keep the folders you are in as a stack: a name is pushed with
append(), and..pops the last one, but only if there is one. - At the end,
"/" + "/".join(folders)builds the answer. With no folders left that is just"/".
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
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
Run your code to see how it does on the test cases, or Submit to check every test.