Birthday Paradox in Python with monte carlo method?

597 Views Asked by At

Trying to find the smallest # of people needed to "enter" a room to have a probability of at least 50% for two people sharing the same birthday, using the monte carlo method (the well known solution is 23 people, but I cant seem to find my errors in logic, or implementation)

1

There are 1 best solutions below

0
Prune On

The error is in expressing how you look for an existing date:

if date in [dates]:

Let's just take the case where you've already found dates 3 and 15, and you just drew another 15 birthday. This check statement evaluates as

if 15 in [ [3, 15] ]:

This is False! The expression on the right has one element, a list. There is no way that an integer (15) and a list ([3, 15]) can be equal, so the check will always fail. Instead, use the in check as seen in your tutorials:

if date in dates:

Output:

double birthday 1
double birthday 2
double birthday 3
double birthday 4
double birthday 5
double birthday 6
double birthday 7
double birthday 8
double birthday 9
double birthday 10
double birthday 11
double birthday 12
double birthday 13
13.0

Yes, you have a couple more errors in your code. You printed a counter instead of the duplicates date, and you reset counter every time through the loop, so your final proportion is always dividing by 1.

Once you fix those, the output will look like

double birthday 204
double birthday 40
double birthday 268
double birthday 260
double birthday 188
double birthday 136
double birthday 324
0.07

Finally, your problem description says that you exit the loop when you find a duplicate. As the above output shows, this is not what you're doing. You will need a break statement for that.