part2.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import argparse
  2. from typing import List, Set
  3. import pprint
  4. import sys
  5. parser = argparse.ArgumentParser()
  6. parser.add_argument("ifile", type=argparse.FileType('r'))
  7. args = parser.parse_args()
  8. lines = [line.replace(" ", " ").strip() for line in args.ifile.readlines()]
  9. number_calls = [num for num in lines[0].strip().split(',')]
  10. boards = [[line.split(' ') for line in lines[x:x+5]] for x in range(2, len(lines), 6)]
  11. def winning_board(board: List[List[str]], called_numbers: Set[str]) -> bool:
  12. for i in range(0, 5):
  13. if all([board[i][col] in called_numbers for col in range(0, 5)]):
  14. return True
  15. if all([board[row][i] in called_numbers for row in range(0, 5)]):
  16. return True
  17. return False
  18. def score_board(board: List[List[str]], called_numbers: Set[str]) -> int:
  19. return sum([int(num) for row in board for num in row if num not in called_numbers])
  20. called_numbers: Set[str] = set()
  21. most_recent = None
  22. boards_that_have_won: Set[int] = set()
  23. for number in number_calls:
  24. called_numbers.add(number)
  25. for index, board in enumerate(boards):
  26. if not (index in boards_that_have_won) and winning_board(board, called_numbers):
  27. boards_that_have_won.add(index)
  28. most_recent = score_board(board, called_numbers) * int(number)
  29. print(most_recent)