Get startedGet started for free

National elections

This exercise will give you a taste of how you can model a DGP at different levels of complexity.

Consider national elections in a country with two political parties - Red and Blue. This country has 50 states and the party that wins the most states wins the elections. You have the probability \(p\) of Red winning in each individual state and want to know the probability of Red winning nationally.

Let's model the DGP to understand the distribution. Suppose the election outcome in each state follows a binomial distribution with probability \(p\) such that \(0\) indicates a loss for Red and \(1\) indicates a win. We then simulate a number of election outcomes. Finally, we can ask rich questions like what is the probability of Red winning less than 45% of the states?

This exercise is part of the course

Statistical Simulation in Python

View Course

Exercise instructions

  • Simulate one election using np.random.binomial() with p = probs and n=1. Assign it to election.
  • Append the average of Red's wins in election to outcomes.
  • Calculate the fraction of outcomes where Red won less than 45% of the states. Save it as prob_red_wins and use it to print your results.

Hands-on interactive exercise

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

outcomes, sims, probs = [], 1000, p

for _ in range(sims):
    # Simulate elections in the 50 states
    election = ____
    # Get average of Red wins and add to `outcomes`
    outcomes.append(____)

# Calculate probability of Red winning in less than 45% of the states
prob_red_wins = ____
print("Probability of Red winning in less than 45% of the states = {}".format(____))
Edit and Run Code