用python编写“生日悖论”的解决方法that if 23 people are selected at random,there is better than 50% chance that at least two of them will have the same birthday (not considering the birth year).You are to write a Python function to simu
来源:学生作业帮助网 编辑:六六作业网 时间:2024/12/28 05:09:00
用python编写“生日悖论”的解决方法that if 23 people are selected at random,there is better than 50% chance that at least two of them will have the same birthday (not considering the birth year).You are to write a Python function to simu
用python编写“生日悖论”的解决方法
that if 23 people are selected at random,there is better than 50% chance that at
least two of them will have the same birthday (not considering the birth year).
You are to write a Python function to simulate selecting n people at random
and checking the probability of having at least two people with the same
birthday.You should ignore the leap years and assume 365-day years.To be
more specific,devise a Python function,call it bdp(n,k),that once invoked,will
select n numbers with replacement from the set of numbers 1 through 365
inclusive,determine if two or more of the numbers selected are the same (call
it a hit),and repeat this task k times,and finally return the percentage of the
hits.Plot your results similar to the graph in the above URL.
用python编写“生日悖论”的解决方法that if 23 people are selected at random,there is better than 50% chance that at least two of them will have the same birthday (not considering the birth year).You are to write a Python function to simu
import random
def bdp(n,k):
\x09 cv = []
\x09 for i in range(k):
\x09\x09 m = []
\x09\x09 for j in range(n):
\x09\x09\x09 m.append(random.randint(1,365))
\x09\x09 counter = 0
\x09\x09 for k1 in m:
\x09\x09\x09 for k2 in m:
\x09\x09\x09\x09 if k1 == k2:
\x09\x09\x09\x09\x09 counter += 1
\x09\x09 cv.append(float(counter/2)/float(n))
\x09 ss = 0
\x09 for i in cv:
\x09\x09 ss += i
return ss/float(len(cv))
亲测能用: