57 lines
1.8 KiB
Python
57 lines
1.8 KiB
Python
#!/usr/bin/env python
|
|
# 2022 - Advent Of Code 7 part 2
|
|
|
|
# file = 'input_example.txt'
|
|
file = 'input.txt'
|
|
|
|
dir_history = ""
|
|
dir_size = {}
|
|
cur_dir = ''
|
|
with open(file, encoding="utf-8") as f:
|
|
for line in f.readlines():
|
|
if line.startswith('$'):
|
|
command = line.strip().split(' ')[1]
|
|
# print(f'command: {command} received')
|
|
if command == 'ls':
|
|
print(f'listing directory {dir_history}')
|
|
elif command == 'cd':
|
|
new_dir = line.strip().split(' ')[2]
|
|
if new_dir == '..':
|
|
cur_size = dir_size[dir_history]
|
|
dir_history = dir_history[:dir_history.rfind('/')]
|
|
dir_size[dir_history] += cur_size
|
|
print(f'back to directory {dir_history}')
|
|
else:
|
|
if new_dir.endswith('/'):
|
|
dir_history += new_dir
|
|
else:
|
|
dir_history += "/" + new_dir
|
|
print(f'changing directory to {dir_history}')
|
|
dir_size[dir_history] = 0
|
|
else:
|
|
if line.startswith('dir'):
|
|
directory = line.strip().split(' ')[1]
|
|
print(f'found dir {directory}')
|
|
else:
|
|
size, filename = line.strip().split(' ')
|
|
print(f'found file {filename} of size {size}')
|
|
dir_size[dir_history] += int(size)
|
|
|
|
|
|
# back to root to account dirs
|
|
while len(dir_history) > 1:
|
|
cur_size = dir_size[dir_history]
|
|
dir_history = dir_history[:dir_history.rfind('/')]
|
|
dir_size[dir_history] += cur_size
|
|
|
|
print(dir_size)
|
|
|
|
needed_space = 30000000 - (70000000 - dir_size['/'])
|
|
print(f'needed space: {needed_space}')
|
|
|
|
sizes = list(dir_size.values())
|
|
sizes.sort()
|
|
for s in sizes:
|
|
if s > needed_space:
|
|
print(s)
|
|
break
|