简体   繁体   中英

Itertools ( groupby function ) with python 3.5

Im trying to figure what is going wrong with my code. Im trying to get right result but it's come out always random answer. Let's says for example I shuffle [ V, V, V, A, V ] I want the result to be [4, 1] but it comes out as [2, 1, 2]. Can you help me ?

class Combinaison:

    types_cartes = [
        Carte.AS, Carte.ROI, Carte.DAME, Carte.VALET, Carte.DIX, Carte.NEUF
    ]

    def __init__(self, des=None):
        self.nb_lancers = 1
        if des is None:
            self.des = self._lancer_des(5)
        else:
            self.des = des
    def determiner_type_combinaison_sans_as(self):

        valeurs = [len(list(group)) for key, group in groupby(des)]
        valeurs.sort(reverse=True)

        sequence1 = [0, 1, 2, 3, 4]
        sequence2 = [1, 2, 3, 4, 5]

        if valeurs == sequence1 or valeurs == sequence2:
            return " straight "

        elif valeurs[0] == 5:
            return " five of a kind "

        elif valeurs[0] == 4:
            return " four of a kind "

        elif valeurs[0] == 3:
            if valeurs[1] == 2:
                return " Fullhouse "
            else:
                return " three of a kind"

        elif valeurs[0] == 2:
            if valeurs[1] == 2:
                return " two pairs"
            else:
                return " one pair"

        else:
            return " nothing good, reshuffle"

class Carte(Enum):
    """Énumeration des types de cartes."""
    AS = 0
    ROI = 1
    DAME = 2
    VALET = 3
    DIX = 4
    NEUF = 5

    def __str__(self):
        if self == Carte.AS:
            return "A"
        if self == Carte.ROI:
            return "R"
        if self == Carte.DAME:
            return "D"
        if self == Carte.VALET:
            return "V"
        if self == Carte.DIX:
            return "X"
        if self == Carte.NEUF:
            return "9"

You need to sort before you groupby . It splits an iterable by equality. It does not accumulate groups.

valeurs = [len(list(group)) for key, group in groupby(sorted(des))]

But it might be better to use the collections.Counter :

valeurs = Counter(des).values()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM