~noelle/aoc-2021

0dee59a9abdfb58cf80f800ee9134d2ac978cb8d — Noelle Leigh 2 years ago 289925e
10_2
1 files changed, 52 insertions(+), 0 deletions(-)

A 10/puzzle_2.py
A 10/puzzle_2.py => 10/puzzle_2.py +52 -0
@@ 0,0 1,52 @@
"""
Solution for AoC 2021 10 Puzzle 2

cat input.txt | python puzzle_2.py
"""
import statistics
import sys

OPENERS = ("(", "[", "{", "<")
CLOSERS = (")", "]", "}", ">")

PAIR_MAP = dict(zip(OPENERS, CLOSERS))

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

if __name__ == "__main__":
    completion_scores = []
    for line in sys.stdin:
        stack = []
        for char in line:
            if not stack:
                stack.append(char)
                continue
            if char in OPENERS:
                stack.append(char)
            if char in CLOSERS:
                stack_head = stack[-1]
                expected_closer = PAIR_MAP[stack_head]
                if char != expected_closer:
                    break
                else:
                    stack.pop()
        else:
            if len(stack):
                # Stack isn't empty, we need to complete the chunks
                completion_string = ""
                while len(stack):
                    stack_head = stack.pop()
                    completion_string += PAIR_MAP[stack_head]
                line_score = 0
                for char in completion_string:
                    line_score *= 5
                    line_score += CLOSER_POINTS[char]
                completion_scores.append(line_score)

    middle_score = statistics.median(sorted(completion_scores))
    sys.stdout.write(str(middle_score))