advent-of-code/src/holt59/aoc/2023/day1.py

50 lines
1.2 KiB
Python
Raw Permalink Normal View History

from typing import Any, Iterator
from ..base import BaseSolver
2023-12-01 09:41:13 +00:00
def find_values(lines: list[str], lookups: dict[str, int]) -> list[int]:
2023-12-01 09:41:13 +00:00
values: list[int] = []
for line in filter(bool, lines):
first_digit = min(
lookups,
key=lambda lookup: index
if (index := line.find(lookup)) >= 0
else len(line),
)
last_digit = max(
lookups,
2023-12-01 19:27:42 +00:00
key=lambda lookup: index if (index := line.rfind(lookup)) >= 0 else -1,
2023-12-01 09:41:13 +00:00
)
2023-12-01 19:27:42 +00:00
2023-12-01 09:41:13 +00:00
values.append(10 * lookups[first_digit] + lookups[last_digit])
return values
class Solver(BaseSolver):
def solve(self, input: str) -> Iterator[Any]:
lookups_1 = {str(d): d for d in range(1, 10)}
lookups_2 = lookups_1 | {
d: i + 1
for i, d in enumerate(
(
"one",
"two",
"three",
"four",
"five",
"six",
"seven",
"eight",
"nine",
)
)
}
lines = input.splitlines()
yield sum(find_values(lines, lookups_1))
yield sum(find_values(lines, lookups_2))