aoc2023/solve.py

38 lines
710 B
Python
Raw Normal View History

2023-12-01 10:23:08 -05:00
#!/usr/bin/env python3
2023-12-01 09:29:09 -05:00
import sys
2023-12-01 12:01:22 -05:00
import re
2023-12-01 10:23:08 -05:00
num_values = dict(
2023-12-01 12:06:35 -05:00
on="1",
tw="2",
thre="3",
2023-12-01 12:01:22 -05:00
four="4",
2023-12-01 12:06:35 -05:00
fiv="5",
2023-12-01 12:01:22 -05:00
six="6",
2023-12-01 12:06:35 -05:00
seve="7",
eigh="8",
nin="9",
2023-12-01 10:23:08 -05:00
)
2023-12-01 09:29:09 -05:00
2023-12-01 12:06:35 -05:00
nums_re = r"on(?=e)|tw(?=o)|thre(?=e)|four|fiv(?=e)|six|seve(?=n)|eigh(?=t)|nin(?=e)|1|2|3|4|5|6|7|8|9"
2023-12-01 12:01:22 -05:00
2023-12-01 09:29:09 -05:00
sum = 0
for line in sys.stdin:
2023-12-01 12:01:22 -05:00
first = len(line)
last = 0
nums = []
2023-12-01 12:06:35 -05:00
for m in re.finditer(nums_re, line):
nums.append((m.start(), m.group(0)))
2023-12-01 12:01:22 -05:00
nums.sort()
first_word = nums[0][1]
last_word = nums[-1][1]
first_word = num_values.get(first_word, first_word)
last_word = num_values.get(last_word, last_word)
value = int(first_word + last_word)
2023-12-01 09:29:09 -05:00
sum += value
print(sum)