-
Notifications
You must be signed in to change notification settings - Fork 0
/
day1.py
89 lines (79 loc) · 1.92 KB
/
day1.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import re
TEST = """1abc2
pqr3stu8vwx
a1b2c3d4e5f
treb7uchet
"""
TEST_BONUS = """two1nine
eightwothree
abcone2threexyz
xtwone3four
4nineightseven2
zoneeight234
7pqrstsixteen
"""
def clean_input(input):
return input.strip().splitlines()
def lfind_digi(s):
for c in s:
if c.isdigit():
return c
return ''
WORD_MAP = {
'one': '1',
'two': '2',
'three': '3',
'four': '4',
'five': '5',
'six': '6',
'seven': '7',
'eight': '8',
'nine': '9'
}
def lfind_word_or_digi(s):
matchgroup = re.match(r'.*?([1-9]|one|two|three|four|five|six|seven|eight|nine)', s)
if matchgroup:
num = matchgroup.group(1)
if num.isdigit():
return num
else:
return WORD_MAP[num]
return ''
def rfind_word_or_digi(s):
matchgroup = re.match(r'.*([1-9]|one|two|three|four|five|six|seven|eight|nine)', s)
if matchgroup:
num = matchgroup.group(1)
if num.isdigit():
return num
else:
return WORD_MAP[num]
return ''
def solve(input):
nums = [f'{lfind_digi(l)}{lfind_digi(reversed(l))}' for l in clean_input(input)]
ans = sum([int(n) for n in nums])
return ans
def solve_bonus(input):
nums = [f'{lfind_word_or_digi(l)}{rfind_word_or_digi(l)}' for l in clean_input(input)]
ans = sum([int(n) for n in nums])
return ans
def test():
ans = solve(TEST)
assert ans == 142
def test_bonus():
ans = solve_bonus(TEST_BONUS)
assert ans == 281
def main():
test()
test_bonus()
with open('input') as f:
fileinput = f.read()
ans = solve(fileinput)
print("Part 1")
print(ans)
with open('input') as f:
fileinput = f.read()
ans = solve_bonus(fileinput)
print("Part 2")
print(ans)
if __name__ == "__main__":
main()