-
Notifications
You must be signed in to change notification settings - Fork 0
/
advent01.py
executable file
·62 lines (48 loc) · 1.53 KB
/
advent01.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#!/usr/bin/env python3
"""
https://adventofcode.com/2023/day/1
Usage:
cat advent01.input | ./advent01.py
"""
import sys
import re
def main ():
input = sys.stdin.read().strip().split('\n')
print("Part 1:", part1(input))
# 54561
print("Part 2:", part2(input))
# 54076
def part1 (input):
sum = 0
for line in input:
digits = list(filter(lambda i: i.isdigit(), line))
first_digit = int(digits[0])
last_digit = int(digits[-1])
sum = sum + first_digit * 10 + last_digit
return sum
def part2 (input):
sum = 0
for line in input:
line = replace_number_words_with_digits(line)
digits = list(filter(lambda i: i.isdigit(), line))
first_digit = int(digits[0])
last_digit = int(digits[-1])
sum = sum + first_digit * 10 + last_digit
return sum
def replace_number_words_with_digits (line):
# Problem here:
# If we replace "two" with "2", we burn the "t" in "eightwo"
# and the follow search for "eight" find "eigh2".
# So we preserve the original string on both sides:
line = re.sub(r"one", "one1one", line)
line = re.sub(r"two", "two2two", line)
line = re.sub(r"three", "three3three", line)
line = re.sub(r"four", "four4four", line)
line = re.sub(r"five", "five5five", line)
line = re.sub(r"six", "six6six", line)
line = re.sub(r"seven", "seven7seven", line)
line = re.sub(r"eight", "eight8eight", line)
line = re.sub(r"nine", "nine9nine", line)
return line
if __name__ == '__main__':
main()