diff options
-rw-r--r-- | 18.py | 26 |
1 files changed, 12 insertions, 14 deletions
@@ -29,7 +29,7 @@ def parse(s): return eval(s.replace('[', 'Pair(').replace(']', ')')) with open_day(18) as f: homework = [parse(l) for l in f] -def try_explode(n): +def try_explode(n, depth=0): def try_add(n, val, access, primary, secondary): if val == 0: return 0 content = access(n) @@ -39,19 +39,17 @@ def try_explode(n): val = try_add(content, val, primary, primary, secondary) val = try_add(content, val, secondary, primary, secondary) return val - def descend(n, depth=0): - if not is_pair(n): return None - if depth == 4: return n - car_val = descend(n.car, depth + 1) - if car_val is not None: - if depth == 3: n.car = 0 - return Pair(car_val.car, try_add(n, car_val.cdr, cdr, car, cdr)) - else: - cdr_val = descend(n.cdr, depth + 1) - if cdr_val is not None: - if depth == 3: n.cdr = 0 - return Pair(try_add(n, cdr_val.car, car, cdr, car), cdr_val.cdr) - return descend(n) + if not is_pair(n): return None + if depth == 4: return n + car_val = try_explode(n.car, depth + 1) + if car_val is not None: + if depth == 3: n.car = 0 + return Pair(car_val.car, try_add(n, car_val.cdr, cdr, car, cdr)) + else: + cdr_val = try_explode(n.cdr, depth + 1) + if cdr_val is not None: + if depth == 3: n.cdr = 0 + return Pair(try_add(n, cdr_val.car, car, cdr, car), cdr_val.cdr) tests = [ ('[[[[[9,8],1],2],3],4]', '[[[[0,9],2],3],4]'), |