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的选择没有做任何事情 - 我想说明这个概念)。
答案 0 :(得分:2)
您忘记重置numberOfDoors
(仍然关闭的门的数量,对吗?)回到3.由于第一个while True:
的每次迭代代表一个新的游戏节目运行,该节目从最初关闭的所有三扇门开始。
...
while True:
numberOfDoors = 3
try:
doors = [0] * numberOfDoors
doors[randint(0, numberOfDoors - 1)] = 1
...
下次尝试添加print
语句以帮助您进行调试。在这种情况下,在分配汽车后立即添加print doors
表示doors
在第一次迭代后只有两个元素。
答案 1 :(得分:0)
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 successful