summary refs log tree commit diff stats
path: root/day10.py
blob: 5cb1073eb4044686aee7ebfc09c21ca241c6855e (plain) (blame)
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
#!/usr/bin/env python

from collections import deque

pairs = {
    "(" : ")",
    "[" : "]",
    "{" : "}",
    "<" : ">"
}

scores = {
    ")": 3,
    "]": 57,
    "}": 1197,
    ">": 25137
}

scores2 = {
    ")": 1,
    "]": 2,
    "}": 3,
    ">": 4
}

# part 1
score = 0
completion_scores = []
with open("day10.txt") as data:
    for line in data:
        stack = deque()
        invalid = False
        for char in line.strip():
            if char in pairs.keys():
                stack.append(char)
            if char in pairs.values():
                if len(stack) == 0 or pairs[stack[-1]] != char:
                    score += scores[char]
                    invalid = True
                    break
                elif pairs[stack[-1]] == char:
                    stack.pop()
        # part 2
        if not invalid:
            total = 0
            while stack:
                total = (5 * total) + scores2[pairs[stack.pop()]]
            completion_scores.append(total)

print(score)
completion_scores.sort()
print(completion_scores[(len(completion_scores) - 1) // 2])