summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--18.py17
1 files 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]'),