From 3aa15fdbba3989f2cdadca8a939390db26e31430 Mon Sep 17 00:00:00 2001 From: Nikhil Vengal Date: Mon, 8 Dec 2025 10:51:02 -0800 Subject: [PATCH] Llm's idiomatic impl with groupby --- day6/part2.py | 41 +++++++++++++++++++++-------------------- 1 file changed, 21 insertions(+), 20 deletions(-) diff --git a/day6/part2.py b/day6/part2.py index d6d8fb1..007715c 100644 --- a/day6/part2.py +++ b/day6/part2.py @@ -1,31 +1,32 @@ +from itertools import groupby from math import prod from pathlib import Path FILE = "input.txt" -def main(): - raw_lines = Path(FILE).read_text().splitlines() - operators = raw_lines[-1].split() - operands: zip[tuple[str]] = zip(*raw_lines[:-1]) - vals: list[int] = [] - sum = 0 - for val in operands: - if all(v == ' ' or v == '' for v in val): - sum += compute(vals, operators.pop(0)) - vals = [] - continue - vals.append(int("".join(val).strip())) - return sum + compute(vals, operators.pop(0)) +def main(file: str = FILE) -> int: + *value_rows, operator_row = Path(file).read_text().splitlines() + operators = operator_row.split() + + # Columns represent vertical numbers; blank columns separate problems. + columns = ("".join(col).strip() for col in zip(*value_rows)) + operands = ( + [int(n) for n in group] + for is_value, group in groupby(columns, key=bool) + if is_value + ) + + return sum(compute(vals, op) for vals, op in zip(operands, operators)) + def compute(vals: list[int], op: str) -> int: - if op == '+': - return sum(vals) - elif op == '*': - return prod(vals) - else: - print(f"unknown operator: {op}") - return 0 + ops = {"+": sum, "*": prod} + try: + return ops[op](vals) + except KeyError: + raise ValueError(f"unknown operator: {op}") + if __name__ == "__main__": print(main())