Llm's idiomatic impl with groupby
This commit is contained in:
@@ -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())
|
||||
|
||||
Reference in New Issue
Block a user