Biased Coin Flip Histogram
Write a function to simulate flipping a biased coin 20 times in each of 1,000 simulations, where each flip has a 20% chance of landing heads. Then, create a histogram showing the distribution of the number of heads observed in these 1,000 simulations.
Practice this interview question in your preferred .ipynb environment. Psst... Google Colab is a free, online .ipynb environment that is easy to get up and running!
Part 1: Write the coin flipping function
Write a function to simulate the process of flipping a biased coin 20 times in each of 1,000 simulations. The coin has 20% of landing heads.
Consider what parameters you would want to include in your function to make it flexible. For instance:
- Number of Simulations: Should the function allow you to easily change how many times you want to run the simulation?
- Number of Flips per Simulation: Should you be able to specify how many times the coin is flipped in each simulation?
- Bias of the Coin: Should the function let you adjust the probability of landing heads (the bias of the coin)?
Think about how to design the function so that you can easily modify these parameters when needed.
Part 2: Plot the histogram
Generate a histogram to visualize the distribution of the number of heads observed in the 1,000 simulations above.
Part 1: Write the coin flipping function
There are several methods to simulate this scenario, but the most efficient approach is to use functions from libraries that handle binomial distributions, such as numpy or scipy.
For instance, using numpy, you can leverage its built-in binomial distribution function to perform the simulations efficiently:
Pythonimport numpy as np
def simulate_coin_flips(n_simulations, n_flips, p_head):
"""Simulate flipping a coin n_flips times in each of n_simulations simulations."""
results = np.random.binomial(n_flips, p_head, n_simulations)
return results
Part 2: Plot the histogram
To visualize the distribution of the number of heads observed in the 1,000 simulations, we can generate results using the function we have created above and then plot it as a histogram. This allows us to see how frequently each possible number of heads occurred. While this example uses matplotlib for plotting, you may also use other libraries like seaborn to plot your histograms.
Pythonimport matplotlib.pyplot as plt # Run simulation n_simulations = 1000 n_flips = 20 p_head = 0.2 results = simulate_coin_flips(n_simulations, n_flips, p_head) # Create histogram plt.hist(results, bins=range(n_flips + 2), edgecolor='black', color='skyblue') plt.title('Histogram of Number of Heads in 1,000 Simulations') plt.xlabel('Number of Heads') plt.ylabel('Frequency') plt.xticks(range(n_flips + 1)) plt.grid(axis='y', linestyle='--', alpha=0.7) plt.show()
Why does bins=range(n_flips + 2)?
bins=range(n_flips + 2) creates a list of bin edges that goes from 0 up to n_flips + 1. For n_flips = 20, this means bins=range(22). This creates 21 bins:
- Bin 1: [0, 1)
- Bin 2: [1, 2)
- …
- Bin 21: [20, 21)
The +2 ensures that there is a bin edge beyond the maximum number of heads (20) so that the last bin covers up to 20 heads without spilling over.
Example of how the histogram should look like:

The exact shape will vary due to randomness, but the histogram will typically show a distribution centered around the mean number of heads with some variation based on the binomial probability of 20% heads per flip
import random
def coin_flip():
x=4*[0]+[1] res=[] for i in range(20): res.append(random.choice(x))
return res
res=[0,0] # [head,tail]
for j in range(1000):
temp=coin_flip() res[0]+=sum(temp) #head res[1]+=(20-sum(temp)) #tail