Skip to content

Instantly share code, notes, and snippets.

@Mu-adventofcode
Last active May 1, 2022 06:50
Show Gist options
  • Save Mu-adventofcode/78d91c766289d56aaec5893a8c04b2ae to your computer and use it in GitHub Desktop.
Save Mu-adventofcode/78d91c766289d56aaec5893a8c04b2ae to your computer and use it in GitHub Desktop.
Advent of Code 2021 day 10 part 2
# AoC 2021 day 10 part 2
from functools import reduce
from statistics import median
OPENERS = "([{<"
OPPOSITE = {"(": ")", "[": "]", "{": "}", "<": ">"}
POINTS = {")": 1, "]": 2, "}": 3, ">": 4}
CORRUPT = object()
def short_stack(line):
stack = []
for ch in line:
if ch in OPENERS:
stack.append(ch)
else:
prev = stack.pop()
if OPPOSITE[prev] != ch:
return CORRUPT
return stack
def scores(lines):
def ch_score(cs, ch):
return cs * 5 + POINTS[ch]
for line in lines:
stack = short_stack(line)
if stack != CORRUPT:
completion = (OPPOSITE[ch] for ch in stack[::-1])
yield reduce(ch_score, completion, 0)
with open("input_10.txt") as f:
lines = [line.strip() for line in f]
middle = median(scores(lines))
print(middle)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment