Search code examples
pythonplaying-cards

Test 5-card hand for four of a kind


I am trying to test a five card hand to see if it includes four of a kind. Currently I have two functions, convert(x) and draw_n(n). They are defined as:

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

When draw_n(n) is executed with parameter 5 (i.e. draw a 5 card hand), it returns a list with 5 random cards that looks like this:

[(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')]

The number refers to the number of the card (i.e. 0 = Ace, ..., 12 = King), the letter refers to the suit, and the string is the name of the card.

I will be executing this function multiple times within Python, resulting in multiple 5 card hands. I would like to be able to count the number of hands with four of a kind within the list of 5 card hands, but I have not had any luck. Any help would be greatly appreciated!


Solution

  • So you only need a function to tell you if it's a four-of-a-kind. Something like this should do:

    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]
    

    I recommend always having sorted hands (by card value), it makes all the process of figuring out what hand you're holding much easier.

    Now use it in the resulting number of hands:

    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)