Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import re
- from itertools import chain
- class Directory:
- def __init__(self, identity, parent=None):
- self.identity = identity
- self.parent = parent
- self.contents = []
- self.size = 0
- def add(self, identity, type, parent, size=None):
- if type == 'file':
- self.contents.append(File(identity, size))
- else:
- self.contents.append(Directory(identity, self))
- self.parent = parent
- size = self.get_size()
- def get_size(self):
- size = 0
- for item in self.contents:
- if isinstance(item, File):
- size += int(item.size)
- else:
- size += int(item.get_size())
- return size
- def iterable_of_sizes(self):
- return chain([self.size],
- *[child.iterable_of_sizes() for child in self.contents])
- def cd(self, command):
- if command == '..':
- return self.parent
- elif command == '/':
- return Directory(command)
- else:
- for i in self.contents:
- if i.identity == command:
- return i
- class File:
- def __init__(self, identity, size):
- self.identity = identity
- self.size = size
- def iterable_of_sizes(self):
- return chain([self.size])
- with open("input_7.txt", "r+")as input_file:
- blocks = [x.rstrip().split("\n") for x in re.split(r"(?=\$)", input_file.read())]
- location = None
- for block in blocks:
- match block[0].split():
- case ["$", "ls"]:
- for entry in block[1:]:
- if entry.split()[0].isnumeric():
- location.add(entry.split()[-1], 'file', location, entry.split()[0])
- else:
- location.add(entry.split()[-1], location, 'directory')
- case ["$", "cd", directory]:
- if not location:
- location = Directory(directory)
- location = location.cd(directory)
- print(location)
- print([item for item in location.iterable_of_sizes()])
Advertisement
Add Comment
Please, Sign In to add comment