-
Notifications
You must be signed in to change notification settings - Fork 0
/
10-syntax-scoring.py
49 lines (41 loc) · 1.47 KB
/
10-syntax-scoring.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
import os
FILENAME = os.path.splitext(__file__)
PUZZLE_INPUT = os.path.join('.', 'puzzle-inputs', f'{FILENAME[0]}.txt')
class Syntax:
def __init__(self):
self.pairs = {'(': ')', '[': ']', '{': '}', '<': '>'}
def load_input(self):
with open(PUZZLE_INPUT, 'r') as f:
for row in f.read().splitlines():
yield row
def is_corrupted(self, line):
stack = []
for char in line:
if char in self.pairs:
stack.append(char)
else:
bracket = stack.pop()
if self.pairs[bracket] != char:
return (True, char)
return (False, stack)
def solution_one(self):
error_scores = {')': 3, ']': 57, '}': 1197, '>': 25137}
score = 0
for line in self.load_input():
corrupted, char = self.is_corrupted(line)
if corrupted:
score += error_scores[char]
return score
def solution_two(self):
complete_scores = {')': 1, ']': 2, '}': 3, '>': 4}
line_scores = []
for line in self.load_input():
score = 0
corrupted, stack = self.is_corrupted(line)
if not corrupted:
for bracket in reversed(stack):
score *= 5
score += complete_scores[self.pairs[bracket]]
line_scores.append(score)
line_scores.sort()
return line_scores[len(line_scores) // 2]