【发布时间】: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