advent_of_code_2021

My attempts to work through the 2021 Advent of Code problems.
git clone https://git.eamoncaddigan.net/advent_of_code_2021.git
Log | Files | Refs | README | LICENSE

day10_part1.py (2289B)


      1 #!/usr/bin/env python
      2 """Advent of Code 2021, day 10 (part 1): Syntax Scoring
      3 For part 1, we are finding 'corrupted' lines from the navigation subsystem
      4 (ones that have mismatched brackets) and scoring them."""
      5 
      6 # I'm not going to bother trying to use pandas for this one.
      7 
      8 from typing import List
      9 from utils import get_puzzle_input
     10 
     11 EXAMPLE_INPUT = \
     12 """[({(<(())[]>[[{[]{<()<>>
     13 [(()[<>])]({[<{<<[]>>(
     14 {([(<{}[<>[]}>{[]{[(<()>
     15 (((({<>}<{<{<>}{[]{[]{}
     16 [[<[([]))<([[{}[[()]]]
     17 [{[{({}]{}}([{[{{{}}([]
     18 {<[[]]>}<{[{[{[]{()[[[]
     19 [<(<(<(<{}))><([]([]()
     20 <{([([[(<>()){}]>(<<{{
     21 <{([{{}}[<[[[<>{}]]]>[]]
     22 """
     23 
     24 def convert_input_to_list(input_string: str) -> List[str]:
     25     """Convert the puzzle input to a list of strings"""
     26     return input_string.rstrip('\n').split('\n')
     27 
     28 def is_open_bracket(bracket: str) -> bool:
     29     """Returns True iff the character is an open bracket"""
     30     return bracket in '([{<'
     31 
     32 def match_bracket(bracket: str) -> str:
     33     """Given an open bracket, return the matching close bracket"""
     34     return {'(': ')', '[': ']', '{': '}', '<': '>'}[bracket]
     35 
     36 def score_bracket(bracket: str) -> int:
     37     """Given a close bracket, return its associated score"""
     38     return {')': 3, ']': 57, '}': 1197, '>': 25137}[bracket]
     39 
     40 def score_line(line: str) -> int:
     41     """Return the 'score' of a corrupted line, or 0 for lines that are not
     42     corrupt"""
     43     # Going with a straightforward solution here: using a stack, pushing open
     44     # brackets and popping when we find close brackets. If we have the wrong
     45     # close bracket, return a score for the bracket we have, otherwise we
     46     # return 0.
     47     bracket_stack: List[str] = []
     48     for bracket in line:
     49         if is_open_bracket(bracket):
     50             bracket_stack.append(bracket)
     51         else:
     52             if match_bracket(bracket_stack.pop()) != bracket:
     53                 return score_bracket(bracket)
     54     return 0
     55 
     56 def solve_puzzle(input_string: str) -> int:
     57     """Return the numeric solution to the puzzle"""
     58     return sum([score_line(l) for l in convert_input_to_list(input_string)])
     59 
     60 def main() -> None:
     61     """Run when the file is called as a script"""
     62     assert solve_puzzle(EXAMPLE_INPUT) == 26397
     63     print("Score for corrupted lines:",
     64           solve_puzzle(get_puzzle_input(10)))
     65 
     66 if __name__ == "__main__":
     67     main()