我创建了一个程序,可运行100,000次帽子检查问题。它是这样的:
不过,正如您在上面的直方图中所看到的那样,x轴标签并不位于每个条形的中间。而且,在2和3之间应该不存在差距。
这是为什么?
代码:
import matplotlib.pyplot as plt
from random import randint
# Define constant N for number of people
N = 10
# Define constant E for number of experiments
E = 100000
# Define list of number of ppl who got their hat back after each experiment
trials = []
# Run experiement E times
for i in range(E):
# Initialise r as number of people who had their hat returned
r = 0
# Loop through each person in N
for i in range(1, N+1):
# Each person rolls a random number
roll = randint(1, 10)
# If roll equals to i, then ith person received his hat back. So increment r by 1
if roll == i:
r += 1
# Append how many ppl got their hat returned after each trial
trials.append(r)
print(trials)
# Create histogram
plt.hist(trials, 10, rwidth=0.8)
# Show histogram
plt.show()