jeudi 26 novembre 2020

Simulate an election

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_1 == 'win':
      tally+=1
    elif region_3 == 'win':
      tally+=1
  elif region_3 == 'win':
    if region_1 == 'win':
      tally+=1
    elif region_2 == '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?




Aucun commentaire:

Enregistrer un commentaire