• [^] # Re: Besoin d'énumérations ordonnées

    Posté par (Mastodon) . En réponse au message Advent of Code 2023, day 7. Évalué à 2. Dernière modification le 07 décembre 2023 à 15:27.

    Une idée :

    from enum import Enum
    from functools import total_ordering
    @total_ordering
    class Card(Enum):
     JOKER = '*'
     ONE = '1'
     TWO = '2'
     THREE = '3'
     FOUR = '4'
     FIVE = '5'
     SIX = '6'
     SEVEN = '7'
     EIGHT = '8'
     NINE = '9'
     TEN = 'T'
     JACK = 'J'
     QUEEN = 'Q'
     KING = 'K'
     ACE = 'A'
     def __lt__(self, other):
     return self.weight < other.weight
     def __eq__(self, other):
     return self.weight == other.weight
    for i, card in enumerate(Card):
     card.weight = i
    >>> Card('A') > Card('7')
    True
    >>> Card('J') > Card('K')
    False
    >>> a = [Card(x) for x in "A2222"]
    >>> b = [Card(x) for x in "99997"]
    >>> a > b
    True

    Un peu du hack puisque la définition même de la classe est bancale, et qu'il faut modifier après initialisation et avant utilisation, mais ça fonctionne.

    • Yth.