Coin Flipping Game

Python Puzzles

Back to the Python! homepage


Your friend has a coin and asks you if you want to play a game:

“I will flip this coin until the number of heads flipped is equal to the number of tails flipped. Then I will give you a dollar for each time I flipped the coin.”

What are the chances that you play this game with your friend once and he pays you exactly eight dollars?


I first run the simulation 10,000 times (inner loop) and determine the number of iterations where the heads and tails match exactly on the 8th flip.

I then run the above simulation another 10,000 times (outer loop) and take the average of these 10,000 averages.

According to the book, there is a 3.9% chance that you will play this game one time. When running multiple times, I receive an average anywhere from 3.5% to 4.5%.

Here are the results of the print statement after running the code.

The Average is 3.97%
The Minimum is 0.00%
The Maximum is 9.52%
The Standard Deviation is 0.56%
import numpy as np

# initialize empty lists to hold results
exactly_8 = []
result = []

# simulate 10,000 trials
for _ in range(10_000):
      
    # flip a coin 9 times
    for _ in range(10_000):
        arr = np.random.randint(2, size=9)
        heads = []
        tails = []
      
        # count the number of heads and tails
        for x in arr:
            heads.append(1) if x == 1 else tails.append(1)
             
            # if the number of heads equals the number of tails or all 8 coins have been flipped, record the number of coins flipped and break the loop
            if len(heads) == len(tails) or len(heads) + len(tails) == 9:
                result.append(len(heads) + len(tails))  
                break
 
        # calculate the proportion of trials with exactly 8 coins flipped
        exactly_8.append(result.count(8)/len(result))
 
# convert the exactly_8 list to a numpy array and print summary statistics
arr = np.array(exactly_8)
print('The Average is ' + '{0:.2%}'.format(np.average(arr)))
print('The Minimum is ' + '{0:.2%}'.format(np.min(arr)))
print('The Maximum is ' + '{0:.2%}'.format(np.max(arr)))
print('The Standard Deviation is ' + '{0:.2%}'.format(np.std(arr)))