作业帮 > 综合 > 作业

用python编写“生日悖论”的解决方法

来源:学生作业帮 编辑:搜搜考试网作业帮 分类:综合作业 时间:2024/05/10 21:30:17
用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编写“生日悖论”的解决方法
import randomdef 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))
亲测能用: