day 1 part 2 in a single regex

This commit is contained in:
Andy Teijelo 2023-12-01 12:06:35 -05:00
parent 384dbb4e14
commit 1d1277074b

View file

@ -3,27 +3,26 @@ import sys
import re import re
num_values = dict( num_values = dict(
one="1", on="1",
two="2", tw="2",
three="3", thre="3",
four="4", four="4",
five="5", fiv="5",
six="6", six="6",
seven="7", seve="7",
eight="8", eigh="8",
nine="9", nin="9",
) )
patterns = "one two three four five six seven eight nine 1 2 3 4 5 6 7 8 9".split() 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"
sum = 0 sum = 0
for line in sys.stdin: for line in sys.stdin:
first = len(line) first = len(line)
last = 0 last = 0
nums = [] nums = []
for pat in patterns: for m in re.finditer(nums_re, line):
for m in re.finditer(pat, line): nums.append((m.start(), m.group(0)))
nums.append((m.start(), pat))
nums.sort() nums.sort()
first_word = nums[0][1] first_word = nums[0][1]