【问题标题】:Python Poker hand single pair counterPython 扑克手牌单对计数器
【发布时间】:2015-10-01 15:08:23
【问题描述】:

我编写了下面的程序来遍历所有可能的扑克手牌并计算其中有多少手牌是一对

一手牌是任意 5 张牌。
单对是当两张相同等级(数字)的牌和其他 3 张不同等级的牌时,例如(1,2,1,3,4)

我将卡片组表示为数字列表,例如
- 1 = 王牌
- 2 = 两个
- 3 = 三
...
- 11 = 杰克
- 12 = 女王...

该程序似乎可以找到但是, 它找到的单对手数 = 1101984

但根据多个来源,正确答案是 1098240。

谁能看到我的代码中的错误在哪里?

from itertools import combinations
# Generating the deck
deck = []
for i in range(52):
    deck.append(i%13 + 1)

def pairCount(hand):
    paircount = 0
    for i in hand:
        count = 0
        for x in hand:
            if x == i:
                count += 1
        if count == 2:
            paircount += .5 #Adding 0.5 because each pair is counted twice

    return paircount

count = 0
for i in combinations(deck, 5): # loop through all combinations of 5
    if pairCount(i) == 1:
        count += 1

print(count)

【问题讨论】:

  • "...因为每对都被计算两次" 不,不是,如果您使用的是itertools.combinations
  • @CoryKramer 是因为逻辑原因,他在外循环中迭代列表一次,然后在内循环中再次迭代,因此单手中的同一对会出现两次(那时他没有使用的地方combinations)
  • 这部分代码与itertools无关。我的意思是,我将每对计算两次,因为我会单独遇到每对的每个成员,如果这有意义的话
  • 如果同一手牌有同种三和一对怎么办?它仍然被认为是单对吗?
  • 我认为这是一个很好的面试问题。

标签: python combinations probability itertools poker


【解决方案1】:

问题是你的手牌也可以包含以下类型的牌 -

三只一对

您实际上也将其计算为一对。

我修改了代码,只计算手牌的数量,这样它就包含了一个种类的三个以及一个组合在一起的一对。代码 -

deck = []
for i in range(52):
    deck.append((i//13 + 1, i%13 + 1))

def pairCount(hand):
    paircount = 0
    threecount = 0
    for i in hand:
        count = 0
        for x in hand:
            if x[1] == i[1]:
                count += 1
        if count == 2:
            paircount += .5 #Adding 0.5 because each pair is counted twice
        if count == 3:
            threecount += 0.33333333
    return (round(paircount, 0) , round(threecount, 0))

count = 0
for i in combinations(deck, 5):
    if pairCount(i) == (1.0, 1.0):
        count += 1

这个数字算作 - 3744

现在,如果我们从你得到的数字中减去这个数字 - 1101984 - 我们得到你期望的数字 - 1098240

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多