Skip to content

Instantly share code, notes, and snippets.

@tim-hub
Created January 31, 2019 02:13
Show Gist options
  • Save tim-hub/df6387c54b21e900d322a7c291b00998 to your computer and use it in GitHub Desktop.
Save tim-hub/df6387c54b21e900d322a7c291b00998 to your computer and use it in GitHub Desktop.
a path class written in Python (with some test cases)
class Path:
def __init__(self, path):
self.current_path = path
def cd(self, new_path):
positions = self.current_path.split('/')
if new_path == '/..':
return None
if new_path[:2] == '..':
# start with ..
# parent path
parent_path = ''.join(str(p)+'/' for p in positions[:-1])[:-1]
self.current_path = parent_path+new_path[2:]
else:
if '..' in new_path:
# contain parent path
parts = new_path.split('..')
if new_path[:4] == '/../':
self.current_path = parts[1]
elif new_path[0] != '/':
# relative path
pa = self.current_path + '/' + parts[0][:-1]
self.current_path = ''.join(str(p)+'/' for p in pa.split('/')[:-1])+parts[1][1:]
else:
# absolute path
pa = parts[0][:-1]
self.current_path = ''.join(str(p)+'/' for p in pa.split('/')[:-1])+parts[1][1:]
else:
# not conatin parent path
if new_path[0] != '/':
# relative path
self.current_path += '/'+new_path
else:
self.current_path = new_path
path = Path('/a/b/c/d')
path.cd('/a/b/c/d/f')
print(path.current_path)
path.cd('d')
print(path.current_path)
path.cd('../ff/dd')
print(path.current_path)
path.cd('..')
print(path.current_path)
path.cd('/../as')
print(path.current_path)
path.cd('/a/b/c/d/f')
path.cd('/..')
print(path.current_path)
path.cd('a/b/../c/d/f')
print(path.current_path)
path.cd('/a/b/../c/d/f')
print(path.current_path)
path.cd('/a/b/c/d/f')
path.cd('../asd')
print(path.current_path)
@tim-hub
Copy link
Author

tim-hub commented Jan 31, 2019

results

/a/b/c/d/f
/a/b/c/d/f/d
/a/b/c/d/f/ff/dd
/a/b/c/d/f/ff
/as
/a/b/c/d/f
/a/b/c/d/f/a/c/d/f
/a/c/d/f
/a/b/c/d/asd

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment