Day 4 completed
+ refactored day 1 to 3 with black -l 119
This commit is contained in:
38
day4/part2.py
Executable file
38
day4/part2.py
Executable file
@@ -0,0 +1,38 @@
|
||||
#!/usr/bin/env python3.11
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
|
||||
input_file = "input.txt"
|
||||
|
||||
|
||||
@dataclass
|
||||
class Card:
|
||||
winning_numbers: list[int]
|
||||
numbers: list[int]
|
||||
copies: int
|
||||
|
||||
def __hash__(self):
|
||||
return (self.copies, self.winning_numbers, self.numbers).__hash__()
|
||||
|
||||
|
||||
with open(input_file) as input:
|
||||
raw_cards = input.readlines()
|
||||
|
||||
cards = [Card(winning_numbers=[], numbers=[], copies=1) for i in range(len(raw_cards))]
|
||||
|
||||
for line in raw_cards:
|
||||
if match := re.match("Card +(\d+): (.*) \| (.*)", line):
|
||||
card_no = int(match.group(1)) - 1
|
||||
cards[card_no].winning_numbers = list(map(int, re.split(" +", match.group(2).lstrip(" "))))
|
||||
cards[card_no].numbers = map(int, re.split(" +", match.group(3).lstrip(" ")))
|
||||
next_no = card_no + 1
|
||||
for number in cards[card_no].numbers:
|
||||
if number in cards[card_no].winning_numbers:
|
||||
if len(cards) > next_no - 1:
|
||||
cards[next_no].copies += cards[card_no].copies
|
||||
next_no += 1
|
||||
|
||||
the_sum = sum(map(lambda c: c.copies, cards))
|
||||
|
||||
|
||||
print(the_sum)
|
||||
Reference in New Issue
Block a user