-1

我试图写一个“生日悖论”的函数。我在互联网上找到了一些示例,并成功地将所有内容组合在一起并进行了一些修改,但我的程序中仍有一些我不理解的东西。

这是我的程序:

# 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

我不明白这条线是什么意思:

year = [0]*365

为什么我想要这样的列表 [0,0,0,0...] ?

谢谢!内塔,生物系学生

4

2 回答 2

1

year = [0]*365创建一个包含 365 个值为 0 的元素的列表:[0,0,0,0...]

birthday = random.randrange(365)创建一个从 0 到 365 的列表并选择一个随机元素。
https://docs.python.org/2/library/random.html#random.randrange

于 2016-01-15T14:35:07.130 回答
1

因为该算法需要为一年中 365 天的每一天设置一个计数器,如下所示:

   year[birthday] = year[birthday] + 1

为了year[birthday]出现在这个语句中,它必须事先被初始化,并且

    year = [0] * 365

初始化它。

于 2016-01-15T14:54:12.327 回答