【问题标题】:Test 5-card hand for four of a kind测试 5 张牌的手牌中的四种
【发布时间】:2015-09-21 23:27:12
【问题描述】:

我正在尝试测试一手五张牌,看看它是否包括四张牌。目前我有两个函数,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张牌),它会返回一个包含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 张牌手的列表中数出其中有 4 张的手牌数量,但我没有任何运气。任何帮助将不胜感激!

【问题讨论】:

  • 我曾尝试使用 split 和 strip 来单独获取卡片字符串(即“红心 9”等),但我没有运气。

标签: python playing-cards


【解决方案1】:
from operator import itemgetter
from collections import Counter
any(v==4 for k,v in Counter(v[0] for v in my_hand).items())

是一种方法……

【讨论】:

  • 优雅,几乎但(无论如何是 Py3.x)不是一个很好的方法。我没有得到key 关键字arg 到Counter(给出错误),无论如何你需要计数器的items()。这确实做到了:any(v == 4 for v, k in Counter(map(itemgetter(0), my_hand)).items())
【解决方案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)

【讨论】:

  • 这是一个很酷的方法来检查一个类型的四个...我不得不考虑很多...(这很愚蠢,因为它不是很混乱)
  • 我写了一个python扑克游戏,这在很多地方都节省了很多时间(握着手排序)。
  • 如果您在更通用的手部评估器中使用该函数,请不要在该函数内部进行排序。对手进行一次排序,然后允许函数采用排序顺序(也许断言它)。这将大大加快你的速度。
  • @LeeDanielCrocker 这是我的意图,“我建议总是有排序的手(按卡片价值)......”。显然你需要排序一次。
【解决方案3】:

你已经在三元组的第一个元素中获得了卡片的排名。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-24
    • 2011-04-19
    • 1970-01-01
    • 1970-01-01
    • 2017-07-11
    • 2017-05-16
    • 1970-01-01
    • 2011-10-22
    相关资源
    最近更新 更多