Python 3.3: Birthday Probability
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Music Box Puzzles
--
Chapters
00:00 Python 3.3: Birthday Probability
01:11 Accepted Answer Score 4
01:46 Answer 2 Score 1
02:53 Thank you
--
Full question
https://stackoverflow.com/questions/1357...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python
#avk47
ACCEPTED ANSWER
Score 4
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
ANSWER 2
Score 1
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