summaryrefslogtreecommitdiffstats
path: root/1.py
blob: 1c5245807fe46f0c7303d157161c4ee7e8b4f57b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# pyright: strict
import re
from itertools import chain
from sys import stdin

nums = {
    "zero": 0,
    "one": 1,
    "two": 2,
    "three": 3,
    "four": 4,
    "five": 5,
    "six": 6,
    "seven": 7,
    "eight": 8,
    "nine": 9,
}

forward = re.compile("|".join(chain(nums.keys(), (str(n) for n in nums.values()))))
reverse = re.compile(
    "|".join(chain((k[::-1] for k in nums.keys()), (str(n) for n in nums.values())))
)


def p1_impl(s: str) -> int:
    nums = [int(n) for n in s if n.isdigit()]
    return nums[0] * 10 + nums[-1]


def p2_impl(s: str) -> int:
    match = forward.search(s)
    if not match:
        raise ValueError
    num = match.group()
    first = int(nums.get(num, num))
    match = reverse.search(s[::-1])
    if not match:
        raise ValueError
    num = match.group()[::-1]
    last = int(nums.get(num, num))
    return first * 10 + last


inp = [line.rstrip() for line in stdin]
print(sum(p1_impl(i) for i in inp))
print(sum(p2_impl(i) for i in inp))