from random import randint
numberOfDoors = 3
success = 0
attempts = 0
while True:
try:
doors = [0] * numberOfDoors
doors[randint(0, numberOfDoors - 1)] = 1
chosen = randint(0, numberOfDoors - 1)
while numberOfDoors > 2:
notIn = -1
while notIn == -1:
index = randint(0, numberOfDoors - 1)
if doors[index] == 0 and index != chosen:
notIn = index
if notIn < chosen:
chosen -= 1
del doors[notIn]
numberOfDoors -= 1
# doors is 2, so not chosen (0 or 1) will return the opposite (1 or 0)
success += doors[not chosen]
attempts += 1
if attempts % 1000000 == 0:
print float(success) / float(attempts)
except KeyboardInterrupt:
print float(success) / float(attempts)
break
经过几个小时的模拟,我的结果几乎准确地达到了50%-我做错什么了吗?
从理论上讲,您选择的门在1/3赔率和2/3赔率之间,因此您至少应该获得高于50的收益。
This答案似乎和我做同样的事情(忽略他对monty的选择不做任何事情-我想举例说明这个概念)。
最佳答案
您忘记了将numberOfDoors
(仍然关闭的门数量,对吗?)重设为3。由于第一个while True:
的每次迭代都代表新的游戏表演,所以表演首先要关闭所有三个门。
...
while True:
numberOfDoors = 3
try:
doors = [0] * numberOfDoors
doors[randint(0, numberOfDoors - 1)] = 1
...
下次,尝试添加
print
语句来帮助您调试。在这种情况下,在分配汽车后立即添加print doors
表示doors
在第一次迭代后仅包含两个元素。关于python - Monty Hall模拟游戏返回50%的赔率?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23820487/