• # En Python

    Posté par (site web personnel) . En réponse au message Advent of Code 2023 : Day 4. Évalué à 4.

    #! /usr/bin/python3
    # Advent of Code 2023, day 4
    from __future__ import annotations
    from collections.abc import Iterable
    from typing import Self
    import re
    class Card:
     def __init__(self, id_: int, win_nums: Iterable[int], got_nums: Iterable[int]):
     self.id = id_
     self.win_nums = set(win_nums)
     self.got_nums = set(got_nums)
     self._matches: Optional[int] = None
     pattern = re.compile(r'^Card +(\d+): ([ \d]+) \| ([ \d]+)\n?$')
     @classmethod
     def import_line(cls, line: str) -> Self:
     if (m := cls.pattern.match(line)) is not None:
     return cls(int(m[1]), (int(word) for word in m[2].split()), (int(word) for word in m[3].split()))
     print(line)
     raise ValueError("invalid card description")
     @property
     def matches(self) -> int:
     if self._matches is None:
     self._matches = len(self.win_nums & self.got_nums)
     assert self._matches is not None
     return self._matches
     @staticmethod
     def _num_to_points(num: int) -> int:
     if num <= 0:
     return 0
     return 2 ** (num - 1)
     def points(self) -> int:
     return self._num_to_points(self.matches)
    def solve_both_parts(lines: aoc.Data) -> tuple[int, int]:
     """Solve puzzle parts 1 and 2: determine the sum of all card values and the total number of cards"""
     # Import
     cards: list[int, Card] = []
     for line in lines:
     card = Card.import_line(line)
     cards.append(card)
     # Part 1
     points = sum(card.points() for card in cards)
     # Part 2
     copies = [1 for card in cards]
     for i, card in enumerate(cards):
     for j in range(i + 1, i + 1 + card.matches):
     copies[j] += copies[i]
     return points, sum(copies)