-
Notifications
You must be signed in to change notification settings - Fork 0
/
day_10.py
114 lines (92 loc) · 2.52 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
import input_10
from aoc import advent_of_code
from pprint import pprint
def to_score(symbol):
table = {
")": 3,
"]": 57,
"}": 1197,
">": 25137,
}
return table[symbol]
def part_one(input):
broken_bits = []
for line in input:
open_stack = []
for char in line:
if char in ["(", "{", "<", "["]:
open_stack.append(char)
if char == ")" and open_stack[-1] != "(":
broken_bits.append(")")
break
if char == "}" and open_stack[-1] != "{":
broken_bits.append("}")
break
if char == ">" and open_stack[-1] != "<":
broken_bits.append(">")
break
if char == "]" and open_stack[-1] != "[":
broken_bits.append("]")
break
if char in [")", "}", ">", "]"]:
open_stack.pop()
return sum(map(to_score, broken_bits))
def to_completer_score(symbols):
table = {
"(": 1,
"[": 2,
"{": 3,
"<": 4,
}
score = 0
for symbol in symbols[::-1]:
score *= 5
score += table[symbol]
return score
def part_two(input):
incomplete_lines = []
for line in input:
good = True
open_stack = []
for char in line:
if char in ["(", "{", "<", "["]:
open_stack.append(char)
if char == ")" and open_stack[-1] != "(":
good = False
break
if char == "}" and open_stack[-1] != "{":
good = False
break
if char == ">" and open_stack[-1] != "<":
good = False
break
if char == "]" and open_stack[-1] != "[":
good = False
break
if char in [")", "}", ">", "]"]:
open_stack.pop()
if good and len(open_stack) > 0:
incomplete_lines.append(to_completer_score(open_stack))
incomplete_lines.sort()
middleIndex = int((len(incomplete_lines) - 1) / 2)
return incomplete_lines[middleIndex]
advent_of_code(
{
"day": 10,
"part": 1,
"fn": part_one,
"sample": input_10.sample(),
"expected": 26397,
"real": input_10.real(),
}
)
advent_of_code(
{
"day": 10,
"part": 2,
"fn": part_two,
"sample": input_10.sample(),
"expected": 288957,
"real": input_10.real(),
}
)