I'm doing birthday paradox, and want to know how many people can meet 0.5 probability that two people have same birthday by using python.

I have tried no using mathematical formula to find probability with given the number of people by using random and randint in python

import random
def random_birthdays():
    bdays = []
    bdays = [random.randint(1, 365) for i in range(23)]
    bdays.sort()
    for x in range(len(bdays)):
        while x < len(bdays)-1:
            print x
            if bdays[x] == bdays[x+1]:
                #print(bdays[x])
                return True
            x+=1
        return False
count  = sum(random_birthdays() for _ in range(1000))
print('In a sample of 1000 classes each with 23 pupils, there were', count, 'classes with individuals with the same birthday')

I expect some hints or codes that can help me through this.

1

There are 1 best solutions below

0
On BEST ANSWER

Well, problem with your code you check only consecutive birthday equality. Better check it using sets

Along the line

import random

def sim(n):
    """simulate birthdays for n people"""
    a = set([random.randint(1, 365) for _ in range(n)])
    if len(a) == n:
        return False
    return True

print(sim(23))
print(sim(23))
print(sim(23))
print(sim(23))
print(sim(23))

Function above will return true if there are same day birthday for n people, false otherwise.

Call it 1000000 times for n = 20, 21, ...., 25 and count how many Trues vs Falses are there

Running code

nt = 0
nf = 0
n = 23
for k in range(0, 1000000):
    if sim(n):
        nt += 1
    else:
        nf += 1

print((nt, nf))

for n = 23 and n = 22 produced

(506245, 493755)
(475290, 524710)