-3
import random

def trial_election(win_chance):
  if random.random() < win_chance:
    return 'win'
  else:
    return 'lose'

region_1 = trial_election(0.87)
region_2 = trial_election(0.65)
region_3 = trial_election(0.17)
  
tally = 0
for trial in range(10_000):
  if region_1 == 'win':
    if region_2 == 'win':
      tally+=1
    elif region_3 == 'win':
      tally+=1
  elif region_2 == 'win':
    if region_3 == 'win':
      tally+=1
    
print(f'The winning percentage is {tally/10_000}')

The request for this code is as such: Suppose two candidates,CandidateA and CandidateB,are running for mayor in a city with three voting regions.The most recent polls show that CandidateA has the following chances for winning in each region:

  • Region1:87percentchanceofwinning
  • Region2:65percentchanceofwinning
  • Region3:17percentchanceofwinning

Write a program that simulates the election ten thousand times and prints the percentage of times in which Candidate Awins.

I only get 1.0 or 0 from running above code, I had expected to get more varieties between 0 and 1, can anyone tell me what is wrong please?

Sam Mason
  • 11,177
  • 1
  • 29
  • 42
Rose
  • 1
  • 1

1 Answers1

1

your code only generates three random values and then checks them 10k times, you instead want to draw values inside the loop, e.g.:

tally = 0
for trial in range(10_000):
  region_1 = trial_election(0.87)
  region_2 = trial_election(0.65)
  region_3 = trial_election(0.17)
  if region_1 == 'win':
    if region_2 == 'win':
      tally+=1
    elif region_3 == 'win':
      tally+=1
  elif region_2 == 'win':
    if region_3 == 'win':
      tally+=1
Sam Mason
  • 11,177
  • 1
  • 29
  • 42