Guest User

Untitled

a guest
Dec 7th, 2022
22
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.13 KB | None | 0 0
  1. import re
  2. from itertools import chain
  3.  
  4.  
  5. class Directory:
  6.  
  7.     def __init__(self, identity, parent=None):
  8.         self.identity = identity
  9.         self.parent = parent
  10.         self.contents = []
  11.         self.size = 0
  12.  
  13.     def add(self, identity, type, parent, size=None):
  14.         if type == 'file':
  15.             self.contents.append(File(identity, size))
  16.         else:
  17.             self.contents.append(Directory(identity, self))
  18.         self.parent = parent
  19.         size = self.get_size()
  20.  
  21.     def get_size(self):
  22.         size = 0
  23.         for item in self.contents:
  24.             if isinstance(item, File):
  25.                 size += int(item.size)
  26.             else:
  27.                 size += int(item.get_size())
  28.         return size
  29.  
  30.     def iterable_of_sizes(self):
  31.         return chain([self.size],
  32.                      *[child.iterable_of_sizes() for child in self.contents])
  33.  
  34.     def cd(self, command):
  35.         if command == '..':
  36.             return self.parent
  37.         elif command == '/':
  38.             return Directory(command)
  39.         else:
  40.             for i in self.contents:
  41.                 if i.identity == command:
  42.                     return i
  43.  
  44.  
  45. class File:
  46.  
  47.     def __init__(self, identity, size):
  48.         self.identity = identity
  49.         self.size = size
  50.  
  51.     def iterable_of_sizes(self):
  52.         return chain([self.size])
  53.  
  54.  
  55. with open("input_7.txt", "r+")as input_file:
  56.     blocks = [x.rstrip().split("\n") for x in re.split(r"(?=\$)", input_file.read())]
  57.     location = None
  58.     for block in blocks:
  59.         match block[0].split():
  60.             case ["$", "ls"]:
  61.                 for entry in block[1:]:
  62.                     if entry.split()[0].isnumeric():
  63.                         location.add(entry.split()[-1], 'file', location, entry.split()[0])
  64.                     else:
  65.                         location.add(entry.split()[-1], location, 'directory')
  66.             case ["$", "cd", directory]:
  67.                 if not location:
  68.                     location = Directory(directory)
  69.                 location = location.cd(directory)
  70.         print(location)
  71.     print([item for item in location.iterable_of_sizes()])
Advertisement
Add Comment
Please, Sign In to add comment