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