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

by Netta   Last Updated October 10, 2019 02:26 AM

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

Answers 2

year = [0]*365 creates a list with 365 elements of the value 0: [0,0,0,0...]

birthday = random.randrange(365) creates a list from 0 to 365 and chooses a random element.
See https://docs.python.org/2/library/random.html#random.randrange

January 15, 2016 14:35 PM

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.

January 15, 2016 14:54 PM

Related Questions

Updated September 21, 2019 06:26 AM

Updated December 06, 2018 06:26 AM

Updated August 25, 2018 14:26 PM

Updated November 16, 2018 21:26 PM

Updated February 13, 2018 15:26 PM