列出所有可能的手牌顺序

Listing all possible sequence of cards in hand

根据定义,序列是至少三张数字序列(连续数字)中的牌的组合。西装无所谓。示例:6♥ 7♥ 8♠ 或 3♦ 4♥ 5♦ 6♥

在这部分代码中,我只能列出三张牌的所有可能组合。假设 self.hand 中的卡片已经按照等级排序。

if len(self.hand) > 2:
    for i in range(len(self.hand)-2):
        for j in range(i+1,len(self.hand)-1):
            for k in range(j+1,len(self.hand)):
                combo = Combo([self.hand[i],self.hand[j],self.hand[k]])
                if combo.isSequence():
                    possibleCombos.append(combo)

我可以为 4 张牌、5 张牌等的序列重复这个类似的代码,但是有没有更紧凑的方法来做到这一点?随着序列变长,我找不到控制多个循环的方法。

By definition, a sequence is a combination of at least three cards that are in a numerical sequence.

我相信这应该有效。我假设一组 5 张不同的牌(1-5)没有花色。我还假设数字必须按升序排列,我需要对此进行澄清(感谢您询问 asongtoruin)。

import itertools 


def all_card_sequences_of_size(cards, n):
    return itertools.combinations(cards, n)  


if __name__ == '__main__':
    cards = [i + 1 for i in range(5)]
    print(list(all_card_sequences_of_size(cards, 3)))
    print(list(all_card_sequences_of_size(cards, 4)))

输出

[(1, 2, 3), (1, 2, 4), (1, 2, 5), (1, 3, 4), (1, 3, 5), (1, 4, 5), (2, 3, 4), (2, 3, 5), (2, 4, 5), (3, 4, 5)]
[(1, 2, 3, 4), (1, 2, 3, 5), (1, 2, 4, 5), (1, 3, 4, 5), (2, 3, 4, 5)]

假设您确实需要序列是连续的,这里有一个解决方案:

import itertools

def is_sequence_consecutive(sequence):
    return all(a == b - 1 for a, b in zip(sequence[:-1], sequence[1:]))


def all_card_sequences_of_size(cards, n):
    for sequence in itertools.combinations(cards, n):
        if is_sequence_consecutive(sequence):
            yield sequence


if __name__ == '__main__':
    cards = [i + 1 for i in range(5)]
    print(list(all_card_sequences_of_size(cards, 3)))
    print(list(all_card_sequences_of_size(cards, 4)))

输出

[(1, 2, 3), (2, 3, 4), (3, 4, 5)]
[(1, 2, 3, 4), (2, 3, 4, 5)]

要获得 n 张牌(n >= 3)的所有可能的连续序列:

import itertools


def is_sequence_consecutive(sequence):
    return all(a == b - 1 for a, b in zip(sequence[:-1], sequence[1:]))


def all_card_sequences_of_size(cards, n):
    for sequence in itertools.combinations(cards, n):
        if is_sequence_consecutive(sequence):
            yield sequence


def all_card_sequences(cards):
    for i in range(3, len(cards) + 1):
        yield from all_card_sequences_of_size(cards, i)


if __name__ == '__main__':
    cards = [i + 1 for i in range(5)]
    print(list(all_card_sequences(cards)))

输出

[(1, 2, 3), (2, 3, 4), (3, 4, 5), (1, 2, 3, 4), (2, 3, 4, 5), (1, 2, 3, 4, 5)]