summaryrefslogtreecommitdiffstats
path: root/10.py
blob: 2eb8c76547f9b84f9cb13feee9a5cbcfbdbe6021 (plain)
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
from dataclasses import dataclass
from enum import Enum
from statistics import median
from utils import open_day

@dataclass
class Chunk:
    begin: str
    end: str
    error_score: int
    completion_score: int

class ChunkType(Enum):
    PAREN  = Chunk('(', ')',     3, 1)
    SQUARE = Chunk('[', ']',    57, 2)
    CURLY  = Chunk('{', '}',  1197, 3)
    ANGLE  = Chunk('<', '>', 25137, 4)

opening = { e.value.begin: e for e in ChunkType }
closing = { e.value.end:   e for e in ChunkType }

error_score = 0
completion_scores = []
with open_day(10) as f:
    for line in f:
        line = line.rstrip()
        stack = []
        for c in line:
            if c in opening:
                stack.append(opening[c])
            else:
                expect = stack.pop()
                got = closing[c]
                if got != expect:
                    error_score += got.value.error_score
                    break
        else:
            score = 0
            while stack:
                completion = stack.pop()
                score *= 5
                score += completion.value.completion_score
            completion_scores.append(score)

print(error_score)
print(median(completion_scores))