From 2a84108f1223acfaa1680995d02686f2260912b2 Mon Sep 17 00:00:00 2001 From: Tomasz Kramkowski Date: Sat, 18 Dec 2021 23:48:33 +0000 Subject: day 18: now concise-er --- 18.py | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/18.py b/18.py index 4281c57..f1b1b86 100644 --- a/18.py +++ b/18.py @@ -41,15 +41,14 @@ def try_explode(n, depth=0): return val 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) + for access in (car, cdr): + val = try_explode(access(n), depth + 1) + if val is None: continue + if depth == 3: access(n, 0) + if access == car: + return Pair(val.car, try_add(n, val.cdr, cdr, car, cdr)) + else: + return Pair(try_add(n, val.car, car, cdr, car), val.cdr) tests = [ ('[[[[[9,8],1],2],3],4]', '[[[[0,9],2],3],4]'), -- cgit v1.2.3-54-g00ecf