编写程序随机产生23个人的生日列表,生日的编号可以简单地认为是从1到365中的任一整数(不需要用年月日表示)。在此基础上,判断产生的列表中是否有两个人(或更多)生日相同。将上面过程重复100000次,记录下这100000次中存在两个(或两个以上)人的生日相同的次数。
时间: 2023-05-12 09:07:22 浏览: 87
这是一个经典的生日悖论问题,可以使用随机数生成器来模拟。以下是一个可能的解决方案:
```python
import random
def generate_birthdays(n):
birthdays = []
for i in range(n):
birthday = random.randint(1, 365)
birthdays.append(birthday)
return birthdays
def has_duplicate(birthdays):
unique_birthdays = set(birthdays)
return len(unique_birthdays) != len(birthdays)
def simulate(n_trials, n_people):
count = 0
for i in range(n_trials):
birthdays = generate_birthdays(n_people)
if has_duplicate(birthdays):
count += 1
return count
n_trials = 100000
n_people = 23
count = simulate(n_trials, n_people)
print(f"Out of {n_trials} trials with {n_people} people, {count} had at least two people with the same birthday.")
```
输出结果可能类似于:
```
Out of 100000 trials with 23 people, 50768 had at least two people with the same birthday.
```
这意味着在23个人中,有两个或更多人生日相同的概率约为50.8%。
阅读全文