-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathday_10.py
71 lines (50 loc) · 1.24 KB
/
day_10.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
points = {ord(')'): 3, ord(']'): 57, ord('}'): 1197, ord('>'): 25137}
points_part_two = {'(': 1, '[': 2, '{': 3, '<': 4}
open_brackets = ('(', '[', '{', '<')
def is_corrupt(a, b):
return abs(ord(a) - ord(b)) > 3
def find_open_brackets(line):
openers = []
score = 0
for c in line.strip():
if c in open_brackets:
openers.append(c)
else:
b = openers.pop()
# End on corrupted lines
if is_corrupt(b, c):
score += points[ord(c)]
break
return (score, openers)
def part_01():
with open('input_10.txt') as d:
score = 0
for line in d:
(line_score, _) = find_open_brackets(line)
score += line_score
return score
def part_02():
with open('input_10.txt') as d:
scores = []
for line in d:
score = 0
openers = []
for c in line.strip():
if c in open_brackets:
openers.append(c)
else:
b = openers.pop()
# End on corrupted lines
if is_corrupt(b, c):
break
else:
# Remove the open brackets one by one and
# calculate the score of the closing bracket
while len(openers):
score *= 5
score += points_part_two[openers.pop()]
scores.append(score)
scores.sort()
return scores[len(scores) // 2]
print('Part 1:', part_01())
print('Part 2:', part_02())