✨ Finishing 7 new elements
This commit is contained in:
59
PyconTW/simplify-unix-path.py
Normal file
59
PyconTW/simplify-unix-path.py
Normal file
@@ -0,0 +1,59 @@
|
||||
def simplify_path(path):
|
||||
"""
|
||||
simplifying a given path
|
||||
"""
|
||||
folders = path.split("/")
|
||||
new_folders = []
|
||||
for folder in folders:
|
||||
if folder == "" or folder == ".":
|
||||
continue
|
||||
elif folder == "..":
|
||||
try:
|
||||
if new_folders[-1] != "..":
|
||||
new_folders.pop()
|
||||
else:
|
||||
new_folders.append("..")
|
||||
except IndexError:
|
||||
if path[0] == "/":
|
||||
print("you can't go deeper than root folder")
|
||||
else:
|
||||
new_folders.append("..")
|
||||
else:
|
||||
new_folders.append(folder)
|
||||
new_folders = "/".join(new_folders)
|
||||
if not path[0].isalpha() and path[0] != ".":
|
||||
new_folders = path[0] + new_folders
|
||||
if len(new_folders) == 0:
|
||||
new_folders = "."
|
||||
print(new_folders)
|
||||
return new_folders
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
# These "asserts" using only for self-checking and not necessary for auto-testing
|
||||
|
||||
# last slash is not important
|
||||
assert simplify_path('/a/') == '/a'
|
||||
|
||||
# double slash can be united in one
|
||||
assert simplify_path('/a//b/c') == '/a/b/c'
|
||||
|
||||
# double dot - go to previous folder
|
||||
assert simplify_path('dir/fol/../no') == 'dir/no'
|
||||
assert simplify_path('dir/fol/../../no') == 'no'
|
||||
|
||||
# one dot means current dir
|
||||
assert simplify_path('/a/b/./ci') == '/a/b/ci'
|
||||
assert simplify_path('vi/..') == '.'
|
||||
assert simplify_path('./.') == '.'
|
||||
|
||||
# you can't go deeper than root folder
|
||||
assert simplify_path('/for/../..') == '/'
|
||||
assert simplify_path('/for/../../no/..') == '/'
|
||||
|
||||
# not all double-dots can be simplyfied in related path
|
||||
assert simplify_path('for/../..') == '..'
|
||||
assert simplify_path('../foo') == '../foo'
|
||||
|
||||
assert simplify_path(".././..") == "../.."
|
||||
print('Simply enough! Let\'s check it now!!')
|
Reference in New Issue
Block a user