pythonfunctionrandomprobabilitybirthday-paradox

What does year = [0]*365 mean in this Python code?


I tried to write a function of 'The Birthday Paradox'. I found some examples in the internet and succseed in combining everything together with some modification but still there are things that I don't understand in my program.

This is my program:

# The Birthday Paradox

print "If there are 23 students in your class, what are the chances that another student and you will have birthday in the same day?"
print ""
print "Use the function has_duplicates(numExamples) to check it out!"
print "Please write in (numExamples) the number of examples of different lists of birthdays of 23-students-classes you want to check."

def has_duplicates(numExamples):

import random
probability = float()

for example in range(numExamples):
   year = [0]*365
   print year
   foundprobability = False
   for i in range(23):
       birthday = random.randrange(365)
       year[birthday] = year[birthday] + 1
       if year[birthday]>1:
          foundprobability = True

   if foundprobability == True:
       probability = probability + 1

countprobabilty = float(probability/numExamples)
print "The probability of a shared birthday in", numExamples,
print "examples of different lists of birthdays of 23-students-classes is", countprobabilty

I dont understand what this line means:

year = [0]*365

why would I want such a list [0,0,0,0...] ?

Thank you! Netta, the biology student


Solution

  • because the algorithm requires a counter for each day of the 365-day year, as follows:

       year[birthday] = year[birthday] + 1
    

    In order for year[birthday] to appear in this statement, it has to have been previously initialized, and

        year = [0] * 365
    

    initializes it.