-
Notifications
You must be signed in to change notification settings - Fork 0
/
day10.py
94 lines (81 loc) · 2.19 KB
/
day10.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
90
91
92
93
94
from util import Day
from aocd import submit
from collections import deque
from statistics import median
pairs = {
"(": ")",
"[": "]",
"{": "}",
"<": ">",
}
def score_syntax_error(corrupted):
points = {
")": 3,
"]": 57,
"}": 1197,
">": 25137,
}
score = 0
for c in corrupted:
score += points[c]
return score
def score_autocomplete(incomplete):
"""Median score of autocomplete."""
# Points for each character (open to save lookup)
points = {
"(": 1,
"[": 2,
"{": 3,
"<": 4,
}
scores = []
for line in incomplete:
score = 0
for c in line:
score *= 5
score += points[c]
scores.append(score)
return median(scores)
def process_syntax(data):
"""Separate lines into corrupted and incomplete."""
corrupted = deque()
incomplete = deque()
# Split data into lines
for line in data:
# Reset deque
last = deque()
# Split line into characters
for char in line:
# If character is an opener bracket, add to deque
if char in pairs.keys():
last.appendleft(char)
else:
# If character is a closer bracket, check if it matches last opener
if char == pairs[last[0]]:
# If it matches, pop last opener
last.popleft()
else:
# If it doesn't match, add to corrupted and skip line
corrupted.appendleft(char)
break
else:
# If line is uncorrupted, add to incomplete
incomplete.append(last)
return corrupted, incomplete
def main(day, part=1):
corrupt, incomplete = process_syntax(day.data)
if part == 1:
return score_syntax_error(corrupt)
if part == 2:
return score_autocomplete(incomplete)
if __name__ == "__main__":
day = Day(10)
day.download()
day.load(typing=str)
p1 = main(day)
print(p1)
submit(p1, part="a", day=10, year=2021)
day.load(typing=str)
p2 = main(day, part=2)
print(p2)
submit(p2, part="b", day=10, year=2021)