The birthday problem is as follows: given a group of n people in a room, what is the probability that two or more of them have the same birthday? It is possible to determine the answer to this question via simulation. Using the starting template provided to you, complete the function called calc birthday probability that takes as input n and returns the probability that two or more of the n people will have the same birthday. To do this, the function should create a list of size n and generate n birthdays in the range 1 to 365 randomly, inclusive of the end-points 1 and 365. It should then check to see if any of the n birthdays are identical. The function should perform this experiment 106 times and calculate the fraction of time during which two or more people had the same birthday. The function will be called as follows from your main program


Import random

def calc_birthday_probability (num_people):
num_tries = le6
num_duplicates = 0

""" FIXME: Complete this function to return the probability of num_people in the room having the same birthday. """

return num_duplicates/num_tries
def main ():
num_people = 10
p = calc_birthday_probability (num_people)

num_people = 20
p = calc_birthday_probability (num_people)

return

# Main program
if __name__ == "_main_":
random.seed (2020)
main ()

Respuesta :

Answer:

import random

def calc_birthday_probability(num_people):

   num_tries = 1e6

   num_duplicates = 0

   tries = 0

   while tries < num_tries:

       total_birthday = {}

       for i in range(1, 366):

           total_birthday[i] = 0

       for count in range(num_people):

           birthday = random.randint(1, 365)

           if total_birthday[birthday] != 0:

               num_duplicates += 1

               break

           total_birthday[birthday] += 1

       tries += 1

   return num_duplicates/num_tries

def main():

   num_people = 10

   p = calc_birthday_probability (num_people)

   print(p)

   num_people = 20

   p = calc_birthday_probability (num_people)

   print(p)

   return

if __name__ == "__main__":

   random.seed(2020)

   main()

Explanation:

  • Run the loop until the value of tries is less than num_tries to do number of trials.
  • Run the loop to create the desired number of birthdays by generating random numbers.
  • Increase  the num_duplicates  variable by 1, if the birthday has  already occurred.
  • Lastly define and then call the main function.