From d4199b281046530aea03ec719e3fe07484970c7c Mon Sep 17 00:00:00 2001 From: Mikael CAPELLE Date: Tue, 13 Dec 2022 08:59:53 +0100 Subject: [PATCH] Clean day 13. --- 2022/day13.py | 42 +++++++++++++++--------------------------- 1 file changed, 15 insertions(+), 27 deletions(-) diff --git a/2022/day13.py b/2022/day13.py index df5c21f..d717412 100644 --- a/2022/day13.py +++ b/2022/day13.py @@ -10,37 +10,25 @@ pairs = [tuple(json.loads(p) for p in block.split("\n")) for block in blocks] def compare(lhs: list[int | list], rhs: list[int | list]) -> int: - if len(lhs) != len(rhs): - m = min(len(lhs), len(rhs)) - r = compare(lhs[:m], rhs[:m]) - if r != 0: - return r + for lhs_a, rhs_a in zip(lhs, rhs): + if isinstance(lhs_a, int) and isinstance(rhs_a, int): + if lhs_a != rhs_a: + return rhs_a - lhs_a else: - return 1 if len(rhs) > len(lhs) else -1 - else: - for lhs_a, rhs_a in zip(lhs, rhs): - if isinstance(lhs_a, int) and isinstance(rhs_a, int): - if lhs_a != rhs_a: - return 1 if rhs_a > lhs_a else -1 - elif isinstance(lhs_a, list) and isinstance(rhs_a, list): - r = compare(lhs_a, rhs_a) - if r != 0: - return r - else: - if not isinstance(lhs_a, list): - lhs_a = [lhs_a] - else: - assert isinstance(rhs_a, int) - rhs_a = [rhs_a] - assert isinstance(rhs_a, list) - r = compare(lhs_a, rhs_a) - if r != 0: - return r - return 0 + if not isinstance(lhs_a, list): + lhs_a = [lhs_a] + elif not isinstance(rhs_a, list): + rhs_a = [rhs_a] + assert isinstance(rhs_a, list) and isinstance(lhs_a, list) + r = compare(lhs_a, rhs_a) + if r != 0: + return r + + return len(rhs) - len(lhs) -answer_1 = sum(i + 1 for i, (lhs, rhs) in enumerate(pairs) if compare(lhs, rhs) == 1) +answer_1 = sum(i + 1 for i, (lhs, rhs) in enumerate(pairs) if compare(lhs, rhs) > 0) print(f"answer_1 is {answer_1}") dividers = [[[2]], [[6]]]