Skip to content

Commit d24248b

Browse files
committed
Day 10 Python solutions
1 parent 03dbe3c commit d24248b

File tree

2 files changed

+94
-0
lines changed

2 files changed

+94
-0
lines changed

10-1.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
#!/usr/bin/env python
2+
3+
from collections import deque
4+
5+
open_tokens = [ '(', '[', '{', '<' ]
6+
close_tokens = [ ')', ']', '}', '>' ]
7+
match = {
8+
'(': ')',
9+
'[': ']',
10+
'{': '}',
11+
'<': '>'
12+
}
13+
14+
score = {
15+
')': 3,
16+
']': 57,
17+
'}': 1197,
18+
'>': 25137
19+
}
20+
21+
lines = [line.strip() for line in open('10.input').readlines()]
22+
lines = [list(line) for line in lines]
23+
24+
errors = []
25+
26+
for line in lines:
27+
stack = deque([])
28+
for token in line:
29+
if token in open_tokens:
30+
stack.append(token)
31+
elif token in close_tokens:
32+
top = stack[-1]
33+
if token == match[top]:
34+
stack.pop()
35+
else:
36+
errors.append(token)
37+
break
38+
39+
print(sum([score[token] for token in errors]))

10-2.py

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
#!/usr/bin/env python
2+
3+
from collections import deque
4+
from math import floor
5+
6+
open_tokens = [ '(', '[', '{', '<' ]
7+
close_tokens = [ ')', ']', '}', '>' ]
8+
match = {
9+
'(': ')',
10+
'[': ']',
11+
'{': '}',
12+
'<': '>'
13+
}
14+
15+
score_table = {
16+
')': 1,
17+
']': 2,
18+
'}': 3,
19+
'>': 4
20+
}
21+
22+
lines = [line.strip() for line in open('10.input').readlines()]
23+
lines = [list(line) for line in lines]
24+
25+
scores = []
26+
27+
for line in lines:
28+
stack = deque([])
29+
corrupted = False
30+
31+
for token in line:
32+
if token in open_tokens:
33+
stack.append(token)
34+
elif token in close_tokens:
35+
top = stack[-1]
36+
if token == match[top]:
37+
stack.pop()
38+
else:
39+
corrupted = True
40+
break
41+
42+
if corrupted or len(stack) == 0:
43+
continue
44+
45+
stack.reverse()
46+
completion = [match[token] for token in stack]
47+
48+
score = 0
49+
for token in completion:
50+
score *= 5
51+
score += score_table[token]
52+
scores.append(score)
53+
54+
scores.sort()
55+
print(scores[floor(len(scores) / 2)])

0 commit comments

Comments
 (0)