I am having issues with the programming the birthday paradox in Python. The birthday paradox basically says that if there are 23 people in a class, the probability that two of them will have the same birthday is 50%.
I have attempted to code this paradox in Python, however it keeps coming back with a probability of closer to 25%. I am very new to Python and so no doubt there is a simple solution to this problem. Here is my code:
import random
def random_birthdays():
bdays = []
bdays = [random.randint(1, 365) for i in range(23)]
bdays.sort()
for x in bdays:
while x < len(bdays)-1:
if bdays[x] == bdays[x+1]:
print(bdays[x])
return True
x+=1
return False
count = 0
for i in range (1000):
if random_birthdays() == True:
count = count + 1
print('In a sample of 1000 classes each with 23 pupils, there were', count, 'classes with individuals with the same birthday')
Error in this line:
for x in bdays:
should be
for x in range(len(bdays)):
Because you need to iterate over indices of birthdays but not birthdays itself.
And one more optimization:
count = 0
for i in range (1000):
if random_birthdays() == True:
count = count + 1
can be replaced by
count = sum(random_birthdays() for _ in range(1000))