46 lines
1015 B
Python
46 lines
1015 B
Python
import string
|
|
import sys
|
|
|
|
lines = sys.stdin.read().split("\n")
|
|
|
|
lookups_1 = {d: int(d) for d in string.digits}
|
|
lookups_2 = lookups_1 | {
|
|
d: i + 1
|
|
for i, d in enumerate(
|
|
(
|
|
"one",
|
|
"two",
|
|
"three",
|
|
"four",
|
|
"five",
|
|
"six",
|
|
"seven",
|
|
"eight",
|
|
"nine",
|
|
)
|
|
)
|
|
}
|
|
|
|
|
|
def find_values(lookups: dict[str, int]) -> list[int]:
|
|
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,
|
|
key=lambda lookup: index if (index := line.rfind(lookup)) >= 0 else 0,
|
|
)
|
|
values.append(10 * lookups[first_digit] + lookups[last_digit])
|
|
|
|
return values
|
|
|
|
|
|
print(f"answer 1 is {sum(find_values(lookups_1))}")
|
|
print(f"answer 2 is {sum(find_values(lookups_2))}")
|