使用python 3.5的Itertools(groupby函数)

时间:2017-04-16 13:16:40

标签: python

我试图弄清楚我的代码出了什么问题。我试图得到正确的结果,但它总是随机回答。让我们说例如我改变[V,V,V,A,V]我希望结果为[4,1],但它出现为[2,1,2]。你能救我吗?

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"

1 个答案:

答案 0 :(得分:1)

您需要在groupby之前进行排序。它通过相等来分割迭代。它不会累积群体。

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

但最好使用collections.Counter

valeurs = Counter(des).values()