diff options
author | Tomasz Kramkowski <tk@the-tk.com> | 2021-12-18 23:39:30 +0000 |
---|---|---|
committer | Tomasz Kramkowski <tk@the-tk.com> | 2021-12-18 23:39:30 +0000 |
commit | 89ffc53ee9f67e509452ea5ac4683d94a62d8c4a (patch) | |
tree | 60dd6000ce5a9d53bd177148d8e30b83be7f0bb8 | |
parent | 016048bc8009016fa3b8748e3afd2ac7a3daf9e3 (diff) | |
download | aoc2021-89ffc53ee9f67e509452ea5ac4683d94a62d8c4a.tar.gz aoc2021-89ffc53ee9f67e509452ea5ac4683d94a62d8c4a.tar.xz aoc2021-89ffc53ee9f67e509452ea5ac4683d94a62d8c4a.zip |
day 18: now less confusing
-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]'), |