我正试图测试一张五张牌,看它是否包含四张牌。目前我有两个功能,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
当使用参数draw_n(n)
执行5
时(即绘制5张牌),它会返回一个包含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 = Ace,...,12 = King),字母是指套装,字符串是卡的名称。
我将在Python中多次执行此函数,从而产生多个5张牌。我希望能够在5张牌手中列出四手牌的数量,但我没有运气。任何帮助将不胜感激!
答案 0 :(得分:3)
from operator import itemgetter
from collections import Counter
any(v==4 for k,v in Counter(v[0] for v in my_hand).items())
是一种方法......
答案 1 :(得分:2)
所以你只需要一个函数来告诉你它是否是四种类型。这样的事情应该做:
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)
答案 2 :(得分:1)
你已经将卡的排名放在三联的第一个元素中。
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