Files
advent-of-code/src/holt59/aoc/2024/day3.py
2024-12-06 14:11:32 +01:00

31 lines
1.1 KiB
Python

import re
from typing import Any, Iterator
from ..base import BaseSolver
class Solver(BaseSolver):
def solve(self, input: str) -> Iterator[Any]:
def extract_multiply(line: str) -> Iterator[int]:
for m in re.finditer(r"mul\(([0-9]{1,3}),\s*([0-9]{1,3})\)", line):
yield int(m.group(1)) * int(m.group(2))
def valid_memory_blocks(line: str) -> Iterator[str]:
accumulate = True
while line:
if accumulate:
if (dont_i := line.find("don't()")) != -1:
yield line[:dont_i]
line, accumulate = line[dont_i:], False
else:
yield line
line = ""
else:
if (do_i := line.find("do()")) != -1:
line, accumulate = line[do_i:], True
else:
line = ""
yield sum(extract_multiply(input))
yield sum(sum(extract_multiply(block)) for block in valid_memory_blocks(input))