我試圖寫一個'生日悖論'的功能。 我在互聯網和succseed中發現了一些例子,將所有的東西結合在一起並進行了一些修改,但仍然存在我在程序中不理解的東西。'生日悖論'
這是我的計劃:
# 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 ... ]?
謝謝! Netta, 生物學學生
'year = [0] * 365'創建一個包含值爲0的365個元素的列表:'[0,0,0,0 ...]' – Oisin
我知道,但爲什麼要創建這樣的列表? – Netta
[在Python中將列表初始化爲已知數量的元素](http://stackoverflow.com/questions/521674/initializing-a-list-to-a-known-number-of-elements-in- python) – rbp