Skip to content

Instantly share code, notes, and snippets.

@samwho
Last active December 1, 2023 22:27
Show Gist options
  • Select an option

  • Save samwho/9a89cea231e51ad6e15ae25c567a0ad3 to your computer and use it in GitHub Desktop.

Select an option

Save samwho/9a89cea231e51ad6e15ae25c567a0ad3 to your computer and use it in GitHub Desktop.
aoc2023-1.py
import re
word_numbers = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
real_numbers = [str(i) for i in range(1, 10)]
numbers_re = "|".join(real_numbers + word_numbers)
first_re = rf"^.*?({numbers_re}).*$"
last_re = rf"^.*({numbers_re}).*?$"
def to_int(number):
if number in word_numbers:
return word_numbers.index(number) + 1
return int(number)
total = 0
for line in open("1.input"):
line = line.strip()
if not line:
continue
first = re.match(first_re, line).group(1)
last = re.match(last_re, line).group(1)
total += int(f"{to_int(first)}{to_int(last)}")
print(total)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment