简体   繁体   English

有没有更简单的方法来解决这个问题使用 python

[英]Is there a simpler way to solve the problem Using python

Python problem: use simulations to estimate the probability that two out of N people in a room share the same birthday. Python 问题:使用模拟来估计一个房间里 N 个人中有两个生日相同的概率。 It is guaranteed that 2 <= N <= 30.保证 2 <= N <= 30。

This is kind of an example:这是一个例子:

import math 

# Returns approximate number of  
# people for a given probability 
def find( p ): 
    return math.ceil(math.sqrt(2 * 365 *
                     math.log(1/(1-p)))); 

# Driver Code 
print(find(0.70)) 

Output 30 Output 30

I think you may have misunderstood your task.我想你可能误解了你的任务。 From the question stated, I would expect a correct solution to look something like the following:根据所述问题,我希望正确的解决方案如下所示:

import random

def contains_duplicates(X):
    seen = set()
    seen_add = seen.add
    for x in X:
        if (x in seen or seen_add(x)):
            return True
    return False


def approximateProbability(num_people, num_tests):
    tests = [[random.randint(1,365) for _ in range(num_people)] for _ in range(num_tests)]
    results = [contains_duplicates(x) for x in tests]
    return results.count(True)/len(results)

# Testing with 23 people and 1000 tests - should return about 0.5
print(approximateProbability(23,1000))

This code takes in the number of people (N) and the number of simulations to run and outputs the percentage of the simulations in which one or more of the people shared a birthday.此代码接受人数 (N) 和要运行的模拟次数,并输出一个或多个人共享生日的模拟百分比。

If that's not what you were after, let me know.如果那不是你想要的,请告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM