day 1 part 2 with internal re module

This commit is contained in:
Andy Teijelo 2023-12-01 12:01:22 -05:00
parent 836fd9941a
commit 384dbb4e14

View file

@ -1,26 +1,38 @@
#!/usr/bin/env python3
import sys
import regex as re
import re
num_values = dict(
one=1,
two=2,
three=3,
four=4,
five=5,
six=6,
seven=7,
eight=8,
nine=9,
one="1",
two="2",
three="3",
four="4",
five="5",
six="6",
seven="7",
eight="8",
nine="9",
)
patterns = "one two three four five six seven eight nine 1 2 3 4 5 6 7 8 9".split()
sum = 0
for line in sys.stdin:
nums = re.findall(r"one|two|three|four|five|six|seven|eight|nine|[1-9]", line, overlapped=True)
nums = [str(num_values.get(x, x)) for x in nums]
first = nums[0]
last = nums[-1]
value = int(first + last)
first = len(line)
last = 0
nums = []
for pat in patterns:
for m in re.finditer(pat, line):
nums.append((m.start(), pat))
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)
sum += value
print(sum)