In: Computer Science
Write a function election(numVoters) that simulates an election between two candidates A and B, with numVoters voters, in which each voter randomly chooses candidate A 55% of the time. Return the fraction (between 0 and 1) of the voters who actually voted for candidate A in your simulation. finished in python
code in python (code to copy)
from random import choices
# This function election(numVoters) simulates
# an election between two candidates A and B,
# with numVoters voters, in which each voter
# randomly chooses candidate A 55% of the time
def election(numVoters):
# candidates in election
candidates = ['A', 'B']
# given in problem description that
# people choose A 55% of the time
# hence we create this distribution
distribution = [0.55, 0.45]
votes_for_A = 0
# loop through number of voters to check their actual vote
for i in range(numVoters):
if(choices(candidates, distribution)[0]=='A'):
votes_for_A = votes_for_A + 1
# return the fraction of people who voted for A
return votes_for_A/numVoters
# Lets do a simulation with 1 million voters
votes_for_A = election(1000000)
print(votes_for_A)
Python code screenshot
Output screenshot
Let me know in the comments if you have any doubts.
Do leave a thumbs up if this was helpful.