Get startedGet started for free

Two of a kind

Now let's use simulation to estimate probabilities. Suppose you've been invited to a game of poker at your friend's home. In this variation of the game, you are dealt five cards and the player with the better hand wins. You will use a simulation to estimate the probabilities of getting certain hands. Let's work on estimating the probability of getting at least two of a kind. Two of a kind is when you get two cards of different suites but having the same numeric value (e.g., 2 of hearts, 2 of spades, and 3 other cards).

By the end of this exercise, you will know how to use simulation to calculate probabilities for card games.

This exercise is part of the course

Statistical Simulation in Python

View Course

Exercise instructions

  • Deal the hand: In the for loop, shuffle deck_of_cards. We then select the first 5 cards as our hand.
  • Count numeric values: Utilize the get() method to construct the dictionary cards_in_hand which counts the occurrence of each numeric_value in hand.
  • Two of a kind? Check if the largest value in cards_in_hand is equal to or greater than 2 to see if we have at least two of a kind. If yes, we increment two_kind.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Shuffle deck & count card occurrences in the hand
n_sims, two_kind = 10000, 0
for i in range(n_sims):
    ____
    hand, cards_in_hand = deck_of_cards[0:5], {}
    for [suite, numeric_value] in hand:
        # Count occurrences of each numeric value
        cards_in_hand[numeric_value] = cards_in_hand.____(numeric_value, 0) + 1
    
    # Condition for getting at least 2 of a kind
    if ____ >=2: 
        two_kind += 1

print("Probability of seeing at least two of a kind = {} ".format(two_kind/n_sims))
Edit and Run Code