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的选择没有做任何事情--我想说明这个概念)。
发布于 2014-05-23 03:38:41
你忘了重新设置numberOfDoors (门的数目仍然关闭,对吗?)回到3,因为第一次while True:的每一次迭代都代表了一次新的游戏表演运行,所以节目开始时所有的三扇门都被关闭了。
...
while True:
numberOfDoors = 3
try:
doors = [0] * numberOfDoors
doors[randint(0, numberOfDoors - 1)] = 1
...下次,尝试添加print语句以帮助您调试。在本例中,在分配car之后立即添加print doors显示,在第一次迭代之后,doors只有两个元素。
发布于 2014-05-23 03:40:45
不久前我自己写了一个Monty Hall模拟问题。也许它会帮助您编写代码--特别是这些注释可能会很有用:
from __future__ import division
import random
results = [] # a list containing the results of the simulations, either 'w' or 'l', win or lose
count = 0
while count <200: #number of simulations to perform
l = []
prize = random.randint(1, 3) #choose the prize door
initialchoice = random.randint(1, 3) #make an initial choice (the door the contestant chooses)
exposed = random.randint(1, 3) #choose the exposed door (the door the host chooses)
while exposed == initialchoice or exposed == prize: #make sure exposed is not same as prize or the initial choice
exposed = random.randint(1, 3)
if initialchoice != prize:
results.append('l') #if the initial choice was incorrect, append 'l'
else:
results.append('w') #if the initial choice was correct, append 'w'
count += 1
print 'prize door:', prize, 'initial choice:',initialchoice, 'exposed door:',exposed #print the results of the simulation
print
w = 0
for i in results:
if i == 'w':
w += 1
print w/len(results) #fraction of times sticking with the original door was successfulhttps://stackoverflow.com/questions/23820487
复制相似问题