Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def day7(s, *, part2=False):
- subdirs_of_dir = collections.defaultdict(list)
- filesize_of_dir = {}
- path = '/'
- for command in s.strip('\n')[2:].split('\n$ '):
- if command == 'cd /':
- path = '/'
- elif command == 'cd ..':
- path = path[:path.rindex('/')]
- elif command.startswith('cd '):
- path += '/' + command[3:]
- else: # command.startswith('ls'):
- filesize = 0
- for line in command[3:].splitlines():
- field, name = line.split()
- if field == 'dir':
- subdirs_of_dir[path].append(f'{path}/{name}')
- else:
- filesize += int(field)
- filesize_of_dir[path] = filesize
- def dirs(dir='/'):
- yield dir
- for dir2 in subdirs_of_dir[dir]:
- yield from dirs(dir2)
- def dir_size(dir):
- return filesize_of_dir[dir] + sum(dir_size(dir2) for dir2 in subdirs_of_dir[dir])
- if not part2:
- return sum(dir_size(dir2) for dir2 in dirs() if dir_size(dir2) <= 100_000)
- needed_space = dir_size('/') - (70_000_000 - 30_000_000)
- 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