From 89ffc53ee9f67e509452ea5ac4683d94a62d8c4a Mon Sep 17 00:00:00 2001 From: Tomasz Kramkowski Date: Sat, 18 Dec 2021 23:39:30 +0000 Subject: day 18: now less confusing --- 18.py | 26 ++++++++++++-------------- 1 file changed, 12 insertions(+), 14 deletions(-) diff --git a/18.py b/18.py index 59c3f8a..4281c57 100644 --- a/18.py +++ b/18.py @@ -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]'), -- cgit v1.2.3-54-g00ecf