#!/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 if sz <= 100000: SIZE.append(sz) return sz sum_sizes(FS) print(sum(SIZE))