Search code examples
pythoncombinationsprobabilitypython-itertoolspoker

Python Poker hand single pair counter


I wrote the program below to iterate through every possible poker hand and count how many of these hands are a single pair

A hand is any 5 cards.
A single pair is when two cards of the same rank (number) and the other 3 cards of all different ranks e.g. (1,2,1,3,4)

I am representing the deck of cards as a list of numbers e.g.
- 1 = ACE
- 2 = Two
- 3 = Three
...
- 11 = Jack
- 12 = Queen...

The program seems to work find however, the number of single pair hands it finds = 1101984

But according to multiple sources the correct answer is 1098240.

Can anyone see where the error in my code is?

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)

Solution

  • The issue is that your hand can contain the following type of cards as well -

    A Three of a kind and a single pair

    You are actually calculating this as a single pair as well.

    I modified the code to count just the number of hands such that it contains a three of a kind as well as a single pair together. Code -

    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
    

    This counted the number as - 3744.

    Now, if we subtract this number from the number you got - 1101984 - We get the number you are expecting - 1098240 .