Skip to main content
 首页 » 编程设计

Python Poker 单对计数器

2025年05月04日12lyhabc

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

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

我将一副纸牌表示为数字列表,例如
- 1 = ACE
- 2 = 二
- 3 = 三
...
- 11 = jack
- 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) 

请您参考如下方法:

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

A Three of a kind and a single pair

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

我修改了代码以仅计算手牌的数量,这样它就包含了三张牌和一对牌。代码-

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。