• # En Python classieux

    Posté par (site web personnel) . En réponse au message Avent du Code, jour 1. Évalué à 4. Dernière modification le 01 décembre 2022 à 14:10.

    Du code commun aux deux parties, essentiellement pour modéliser et importer les données :

    import collections
    import itertools
    from collections.abc import Iterable, Sequence
    import aoc
    class Pack:
     """An elf backpack, containing a list of food items"""
     def __init__(self, items: Sequence[int]) -> None:
     """Create an elf backpack containing the providing items (an item is
     actually an amount of energy, in calories)"""
     self.items = items
     def total(self) -> int:
     """Return the total energy corresponding to the items in a
     backpack"""
     return sum(self.items)
    def import_packs(lines: Iterable[str]) -> Iterable[Pack]:
     """Read input lines and return an iterator, yielding one elf backpack at a
     time"""
     items = [] # type: list[int]
     for line in lines:
     if line == '\n':
     # A newline separates the description of one backpack from the next
     # one. Therefore, a pack has been entirely listed and can be
     # yielded.
     yield Pack(items)
     items = []
     continue
     items.append(int(line))
     # The last pack has been entirely listed and we have to yield it too.
     yield Pack(items)

    Première partie, on veut le total de l'énergie du sac qui en contient le plus :

    def part1(lines: Iterable[str]) -> int:
     """Solve puzzle part 1: determine the backpack containing most energy, and
     return the amount of energy it contains"""
     packs = import_packs(lines)
     return max(pack.total() for pack in packs)

    Deuxième partie, on veut le total de l'énergie des trois sacs qui en contiennent le plus :

    def part2(lines: Iterable[str]) -> int:
     """Solve puzzle part 2: determine the three backpacks containing most
     energy, and return the amount of energy they contain"""
     packs = import_packs(lines)
     totals = (pack.total() for pack in packs)
     # Sort the energy totals so the greatest are at the end, and sum the three
     # last ones
     return sum(sorted(totals)[-3:])

    Je ne suis pas très satisfait par le fait de trier les totaux, j'aurais bien aimé faire ça en parcourant simplement les sacs, mais je n'ai pas trouvé de façon élégante de le faire.