|
| 1 | +# 8.9 - Challenge: Simulate an Election |
| 2 | +# Alternate solution to challenge |
| 3 | + |
| 4 | + |
| 5 | +# Simulate the results of an election using a Monte Carlo simulation |
| 6 | + |
| 7 | +from random import random |
| 8 | + |
| 9 | + |
| 10 | +def run_regional_election(chance_A_wins): |
| 11 | + """Return the result of a regional election, either "A" or "B". |
| 12 | +
|
| 13 | + The chances of "A" winning are determined by chance_A_wins. |
| 14 | + """ |
| 15 | + if random() < chance_A_wins: |
| 16 | + return "A" |
| 17 | + else: |
| 18 | + return "B" |
| 19 | + |
| 20 | + |
| 21 | +def run_election(regional_chances): |
| 22 | + """Return the result of an election, either "A" or "B". |
| 23 | +
|
| 24 | + regional_chances is a list or tuple of floats representing the |
| 25 | + chances that candidate "A" will win in each region. |
| 26 | +
|
| 27 | + For example, run_election([.2, .5, .7]) will run an election with |
| 28 | + three regions, where candidate "A" has a 20% chance to win in the |
| 29 | + first region, 50% in the second, and 70% in the third. |
| 30 | + """ |
| 31 | + num_regions_won_by_A = 0 |
| 32 | + for chance_A_wins in regional_chances: |
| 33 | + if run_regional_election(chance_A_wins) == "A": |
| 34 | + num_regions_won_by_A = num_regions_won_by_A + 1 |
| 35 | + |
| 36 | + # Return the results. Note that the number of regions won by candidate |
| 37 | + # "B" is the total number of regions minus the number of regions won by |
| 38 | + # candidate "A". The total number of regions is the same as the length |
| 39 | + # of the regional_chances list. |
| 40 | + if num_regions_won_by_A > len(regional_chances) - num_regions_won_by_A: |
| 41 | + return "A" |
| 42 | + else: |
| 43 | + return "B" |
| 44 | + |
| 45 | + |
| 46 | +CHANCES_A_WINS_BY_REGION = [0.87, 0.65, 0.17] |
| 47 | +NUM_TRIALS = 10_000 |
| 48 | + |
| 49 | +# Run the Monte-Carlo simulation |
| 50 | +num_times_A_wins = 0 |
| 51 | +for trial in range(NUM_TRIALS): |
| 52 | + if run_election(CHANCES_A_WINS_BY_REGION) == "A": |
| 53 | + num_times_A_wins = num_times_A_wins + 1 |
| 54 | + |
| 55 | +# Display the probabilities that candidate A or candidate B wins the |
| 56 | +# election. Note the probability that B wins can be calculated by |
| 57 | +# subtracting the probability that A wins from 1. |
| 58 | +print(f"Probability A wins: {num_times_A_wins / num_trials}") |
| 59 | +print(f"Probability B wins: {1 - (num_times_A_wins / num_trials)}") |
0 commit comments