aoc
/
2022
1
0
Fork 0
2022/day07.py

44 lines
1.0 KiB
Python
Raw Normal View History

2022-12-24 14:59:27 +00:00
import fileinput
from collections import defaultdict
from pprint import pprint
cwd: list[str] = []
folders: defaultdict[tuple[str, ...], int] = defaultdict(int)
subdirs: defaultdict[tuple[str, ...], list[str]] = defaultdict(list)
for line in fileinput.input():
s = line.split()
if s[0] == "$":
if s[1] == "cd":
if s[2] == "..":
cwd.pop()
elif s[2] == "/":
cwd.clear()
else:
cwd.append(s[2])
else:
if s[0].isdigit():
folders[tuple(cwd)] += int(s[0])
elif s[0] == "dir":
subdirs[tuple(cwd)].append(s[1])
def recur(path: tuple[str, ...]) -> int:
# size = folders[path]
for subdir in subdirs[path]:
folders[path] += recur(path + (subdir,))
return folders[path]
recur(())
pprint(folders)
part1 = sum(x for x in folders.values() if x <= 100_000)
print(part1)
used = folders[()]
free = 70_000_000 - used
need_freed = 30_000_000 - free
print(min(x for x in folders.values() if x > 30_000_000 - free))