Advertisement
hhoppe

Advent of code 2022 day 7

Dec 7th, 2022 (edited)
709
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.10 KB | None | 0 0
  1. def day7(s, *, part2=False):
  2.   subdirs_of_dir = collections.defaultdict(list)
  3.   filesize_of_dir = {}
  4.   path = '/'
  5.   for command in s.strip('\n')[2:].split('\n$ '):
  6.     if command == 'cd /':
  7.       path = '/'
  8.     elif command == 'cd ..':
  9.       path = path[:path.rindex('/')]
  10.     elif command.startswith('cd '):
  11.       path += '/' + command[3:]
  12.     else:  # command.startswith('ls'):
  13.       filesize = 0
  14.       for line in command[3:].splitlines():
  15.         field, name = line.split()
  16.         if field == 'dir':
  17.           subdirs_of_dir[path].append(f'{path}/{name}')
  18.         else:
  19.           filesize += int(field)
  20.       filesize_of_dir[path] = filesize
  21.  
  22.   def dirs(dir='/'):
  23.     yield dir
  24.     for dir2 in subdirs_of_dir[dir]:
  25.       yield from dirs(dir2)
  26.  
  27.   def dir_size(dir):
  28.     return filesize_of_dir[dir] + sum(dir_size(dir2) for dir2 in subdirs_of_dir[dir])
  29.  
  30.   if not part2:
  31.     return sum(dir_size(dir2) for dir2 in dirs() if dir_size(dir2) <= 100_000)
  32.  
  33.   needed_space = dir_size('/') - (70_000_000 - 30_000_000)
  34.   return min(dir_size(dir) for dir in dirs() if dir_size(dir) >= needed_space)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement