Skip to content

Instantly share code, notes, and snippets.

@bearpelican
Created June 12, 2020 21:25
Show Gist options
  • Save bearpelican/54d631fc20798c83331674455255ba69 to your computer and use it in GitHub Desktop.
Save bearpelican/54d631fc20798c83331674455255ba69 to your computer and use it in GitHub Desktop.
#
# Your previous Plain Text content is preserved below:
#
# Design a file system.
# File system only deals with directories
# Handle 3 basic commands.
# mkdir - create 1 or more directories (1 level only)
# ls - list files in current directory
# cd - change directory
# pwd - print working directory
class Directory():
def __init__(self, name):
self.contents = {}
self.name = name
def mkdir(self, *args):
for arg in sorted(args):
self.contents[arg] = Directory(arg)
def get(self, name): return self.contents[name]
def ls(self):
return list(self.contents.keys())
class FileSystem():
def __init__(self):
self.root = Directory('')
self.path = [self.root]
def run(self, command):
cmd, *args = command.split(' ')
if cmd == 'mkdir':
self.loc().mkdir(*args)
elif cmd == 'ls':
return self.loc().ls()
elif cmd == 'cd':
return self.cd(args[0])
elif cmd == 'pwd':
return self.pwd()
def pwd(self):
return '/'.join([d.name for d in self.path])
def loc(self): return self.path[-1]
def cd(self, d):
for p in d.split('/'): self._cd(p)
def _cd(self, p):
if p == '..':
self.path.pop()
else:
self.path.append(self.loc().get(p))
def return_tree(self):
queue = [self.root]
tree = []
while len(queue):
item = queue.pop(0)
for k in item.contents.values():
tree.append(k.name)
queue.append(k)
return tree
# Part 1
fs = FileSystem()
fs.run('mkdir dir1 dir2')
assert fs.run('ls') == ['dir1', 'dir2']
print('MKDIR, LS - Success!')
fs.run('cd dir1')
fs.run('mkdir dir4 dir3')
assert fs.run('ls') == ['dir3', 'dir4']
print('CD - Success!')
fs.run('cd dir3')
assert fs.run('pwd') == '/dir1/dir3'
print('PWD - Success!')
# Part 2
fs.run('mkdir dir5 dir6')
fs.run('cd dir5')
fs.run('mkdir dir_last')
assert fs.run('ls') == ['dir_last']
assert fs.run('pwd') == '/dir1/dir3/dir5'
fs.run('cd ..')
assert fs.run('pwd') == '/dir1/dir3'
print('CD .. - Success!')
# Part 3
fs.run('cd ../../dir2')
fs.run('mkdir dir7 dir8')
assert fs.run('ls') == ['dir7', 'dir8']
print('CD ../.. - Success!')
# Part 4
assert fs.return_tree() == ['dir1', 'dir2', 'dir3', 'dir4', 'dir7', 'dir8', 'dir5', 'dir6', 'dir_last']
print('RETURN_TREE .. - Success!')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment