Created
January 31, 2019 02:13
-
-
Save tim-hub/df6387c54b21e900d322a7c291b00998 to your computer and use it in GitHub Desktop.
a path class written in Python (with some test cases)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
results