aocpy/2021/d10.py
2024-11-21 08:43:15 -05:00

64 lines
1.2 KiB
Python

from lib import get_data
data = get_data(__file__).strip()
OPEN = "([{<"
CLOSE = ")]}>"
def part1(line):
score = {
")": 3,
"]": 57,
"}": 1197,
">": 25137,
}
stack = []
for c in line:
if c in OPEN:
stack.append(OPEN.index(c))
elif c in CLOSE:
ci = CLOSE.index(c)
if stack and stack[-1] == ci:
stack.pop()
continue
else:
return score[c]
else:
assert False
return 0
def part2(line):
stack = []
for c in line:
if c in OPEN:
stack.append(OPEN.index(c))
elif c in CLOSE:
ci = CLOSE.index(c)
if stack and stack[-1] == ci:
stack.pop()
continue
else:
assert False
else:
assert False
score = 0
for v in reversed(stack):
score *= 5
score += v + 1
return score
s1 = 0
s2s = []
for line in data.splitlines():
s = part1(line)
if s == 0:
s2s.append(part2(line))
s1 += s
print(s1)
s2 = sorted(s2s)[len(s2s) // 2]
print(s2)