Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Following specs piecemeal solution in Clear category for Simplify Unix Path by amandel
def simplify_path(path):
"""
simplifying a given path
"""
root = path[0] == '/' # is the path absolute?
blocks = path.split('/')
# remove useless blocks; right to left to avoid indexing errors
for i in range(len(blocks)-1,-1,-1):
if blocks[i] in ('', '.'):
del blocks[i]
# go back with '..' as possible, again right to left
for i in range(len(blocks)-2,-1,-1):
if blocks[i] != '..' and blocks[i+1] == '..':
del blocks[i:i+2]
# absolute paths cannot accept an initial '..'
if root:
while blocks and blocks[0] == '..':
del blocks[0]
final = '/'.join(blocks)
# add initial '/' for absolute paths; empty relative path becoms '.'
return '/' + final if root else final or '.'
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'
print('Simply enough! Let\'s check it now!!')
April 20, 2021