测试四张五张牌

Test 5-card hand for four of a kind

我正在尝试测试一手五张牌,看它是否包含四张。目前我有两个函数,convert(x)draw_n(n)。它们被定义为:

def convert(x):
    card = x % 13
    suit = 'SHDC'[x/13]
    return card, suit, str([card, suit])

def draw_n(n):
    from random import sample

    # initialize the list
    cards = []
    # make sure that we have a valid number
    if n > 0 and n <= 52:
        # sample without replacement 
        for x in sample(xrange(0, 52), n):
            # append the converted card to the list
            cards.append(convert(x))
    return cards

当使用参数 5 执行 draw_n(n) 时(即抽出 5 张手牌),它 returns 一个包含 5 张随机牌的列表,如下所示:

[(8, 'D', '9 of Diamonds'),
 (0, 'H', 'Ace of Hearts'),
 (8, 'H', '9 of Hearts'),
 (10, 'S', 'Jack of Spades'),
 (12, 'C', 'King of Clubs')]

数字是指牌号(即0=A,...,12=K),字母是指花色,字符串是牌名。

我将在 Python 内多次执行此函数,从而产生多手 5 张牌。我希望能够计算出 5 张手牌列表中有 4 手牌的数量,但我没有任何运气。任何帮助将不胜感激!

你已经在三元组的第一个元素中有了卡片的等级。

rank_count = 13*[0]
for card in hand:
   rank = int(card[0])
   rank_count[rank] += 1

if 4 in rank_count:
   # you have a 4-of-a-kind

所以你只需要一个函数来告诉你它是不是一类四。应该这样做:

def is_four_of_a_kind(hand):
    hand = sorted(hand)
    # assumes length >= 5
    return hand[0][0] == hand[3][0] or hand[1][0] == hand[4][0]

我建议总是排序手牌(按牌面值),它使确定你的手牌的所有过程拿着更容易。

现在用在结果手数中:

hands = [draw(5) for _ in xrange(1000)]
four_of_a_kinds = [hand for hand in hands if is_four_of_a_kind(hand)]
four_of_a_kinds_count = len(four_of_a_kinds)
from operator import itemgetter
from collections import Counter
any(v==4 for k,v in Counter(v[0] for v in my_hand).items())

是一种方法...