Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
5 - liner, recursion in recursion =) solution in Creative category for Simplify Unix Path by kdim
import re
def simplify_path(path):
t = ((r'//|/\.(/|$)|^/\.\.(/|$)', '/'), (r'(.+)/$', r'\1'), (r'\w+/\.\.', '.'), (r'^\./', ''))
sub = lambda p, t: sub(re.sub(*t[0], p), t[1:]) if t else p
return path if sub(path, t) == path else simplify_path(sub(path, t))
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!!')
Feb. 11, 2021
Comments: