Reputation: 379
Trying to do the Birthday Program in python. Being a beginner in Python, I am having some trouble.
results should look like:
For 2 people, the probability of 2 birthdays is 0.002.
For 3 people, the probability of 2 birthdays is 0.008. and so on...
Stuck on step 2 & 3:
import random
# not sure what to put for count
count = [random.randint(1, 365)]
def duplicates(l):
if len(l)!=len(set(l)):
return True
else:
return False
def test(count):
return [random.randint(1, 365)]
#def probability(count,num):
I believe I did step one correctly, but I'm not sure where to go from here.
Upvotes: 3
Views: 1750
Reputation: 16242
test
does not return a list of length count
. The result only has one element. You would want to make use of list comprehension to get this to work nice:
[random.randint(1, 365) for x in range(count)]
Then for step 3:
def probability(count,num):
dup_trues = sum([duplicates(test(count)) for i in range(num)]) #***
dup_falses = num-dup_trues
return float(fails)/num
The host important line in the above function is labeled #***
Here's a breakdown of how it works:
The stuff in the square brackets is a list comprehension.
for i in range(num)
says do this stuff with i=0, i=1, ...i=num-1. You know what duplicates and test does. So the list ends up with a bunch of trues and falses (ones and zeros)
sum
adds up the elements of the list. So this gives us the number of trues
The next line dup_falses = num-dup_trues
says we have num results altogether, those that aren't true are false.
return float(fails)/num
the float
is not necessary in python 3
Upvotes: 1
Reputation: 304493
You should create the list like this. test
isn't a very useful name. Consider something like make_birthday_list
instead
def test(count):
return [random.randint(1, 365) for x in range(count)]
The test in duplicates already evaluates to a bool, so you can just do this. It's not a good idea to use l
as a variable name (looks too much like 1
) so I changed it to the_list
def duplicates(the_list):
return len(the_list)!=len(set(the_list))
You'll have to run the test over and over to get the probability
eg.
num_samples = 10000
for count in range(100):
dup = 0
for test_number in range(num_samples):
the_list = make_birthday_list(count)
if duplicates(the_list):
dup += 1
print(count, dup/num_samples) # / returns a float in Python3
Upvotes: 4