-
Notifications
You must be signed in to change notification settings - Fork 28
/
10_path.py
60 lines (45 loc) · 1.37 KB
/
10_path.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
"""
30 min
Write a function that provides change directory (cd) function for an abstract file system.
Notes:
* Root path is '/'.
* Path separator is '/'.
* Parent directory is addressable as '..'.
* Directory names consist only of English alphabet letters (A-Z and a-z).
* The function should support both relative and absolute paths.
* The function will not be passed any invalid paths.
* Do not use built-in path-related functions.
For example:
path = Path('/a/b/c/d')
path.cd('../x')
print(path.current_path)
should display '/a/b/c/x'.
class Path:
def __init__(self, path):
self.current_path = path
def cd(self, new_path):
pass
path = Path('/a/b/c/d')
path.cd('../x')
print(path.current_path)
"""
class Path:
def __init__(self, path):
self.current_path = path
def cd(self, new_path):
if new_path.startswith('/'):
self.current_path = new_path
else:
orig = self.current_path.split('/')
for part in new_path.split('/'):
if part == '..':
orig.pop()
else:
orig.append(part)
if orig == ['']:
self.current_path = '/'
else:
self.current_path = '/'.join(orig)
path = Path('/a/b/c/d')
path.cd('../x')
print(path.current_path)