The birthday problem is as follows given a group of n people
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. Write a function called calcBirthdayProbability that takes as input n and calculates the probability that two or more of the n people will have the same birthday. To do this, the function should create an array of size n and generate n birthdays in the range 1 to 365 randomly. It should then check to see if any of the n birthdays are identical. The function should perform this experiment 10^6 times and calculate the fraction of time during which two or more people had the same birthday. The function is called as follows: probability = calcBirthdayProbability(numPeople) Examples of correct function behavior follow: >> numPeople = 10; >> prob = calcBirthdayProbability(numPeople) prob = 0.1175 >> numPeople = 20; >> prob = calcBirthdayProbability(numPeople) prob = 0.4117 >> prob = calcBirthdayProbability(numPeople) prob = 0.4114 >> prob = calcBirthdayProbability(numPeople) prob = 0.4113 Note that different runs of the program with the same value for numPeople yield slightly different probability results. This is expected since we are performing experiments with randomly generated values during each run of the program. The Cody tests will be designed to account for this type of variation in the results.
Solution
import random
def has_duplicates(listToCheck):#check duplicate dates
number_set = set(listToCheck)
if len(number_set) is not len(listToCheck):
return True
else:
return False
def calcBirthdayProbability(numPeople):#find probability
duplicateNumber=0
for i in range(0,1000):
birthdayList=[]
for j in range(0,numPeople):
birthday=random.randint(1,365)#generate random birthday
birthdayList.append(birthday)
x = has_duplicates(birthdayList)
if x==True:
duplicateNumber+=1
print \"prob\ \"
print round(((duplicateNumber/1000.0)),3)#print probability
numPeople=input(\"Enter numPeople\ \")
calcBirthdayProbability(numPeople)
======================================================
Enter numPeople
10
prob
0.119
