68 lines
1.3 KiB
Python
Executable File
68 lines
1.3 KiB
Python
Executable File
#!/usr/bin/env python
|
|
|
|
import re
|
|
from functools import reduce
|
|
|
|
FS = {}
|
|
POS = [] # empty dict is /
|
|
|
|
def dig(d, keys):
|
|
if keys == []:
|
|
return d
|
|
else:
|
|
return reduce(dict.__getitem__, keys, d)
|
|
|
|
def process_instruction(spec):
|
|
_, cmd, *args = spec.split(" ")
|
|
if cmd == "cd":
|
|
if args[0] == "/":
|
|
POS.clear()
|
|
elif args[0] == "..":
|
|
POS.pop()
|
|
else:
|
|
POS.append(args[0])
|
|
elif cmd != "ls": # nothing to do for ls
|
|
raise "Unknown command: " + spec
|
|
|
|
def process_output(spec):
|
|
cwd = dig(FS, POS)
|
|
size_or_dir, name = spec.split(" ")
|
|
|
|
if size_or_dir == "dir":
|
|
cwd[name] = {}
|
|
else:
|
|
cwd[name] = int(size_or_dir)
|
|
|
|
with open('input') as f:
|
|
# Read the diagram + separating line
|
|
for line in f:
|
|
if line[0] == '$':
|
|
process_instruction(line.rstrip())
|
|
else:
|
|
process_output(line.rstrip())
|
|
|
|
SIZE = []
|
|
|
|
# Recursively sum each dictionary and add the sums together
|
|
def sum_sizes(d):
|
|
sz = 0
|
|
|
|
for v in d.values():
|
|
if isinstance(v, dict):
|
|
sz = sz + sum_sizes(v)
|
|
else:
|
|
sz = sz + v
|
|
|
|
SIZE.append(sz)
|
|
|
|
return sz
|
|
|
|
total_used = sum_sizes(FS)
|
|
space_free = 70000000 - total_used
|
|
target = 30000000 - space_free
|
|
|
|
for v in sorted(SIZE):
|
|
if v >= target:
|
|
print(v)
|
|
break
|