【发布时间】:2017-06-18 19:52:40
【问题描述】:
我一直在尝试在 Python 中解决 monty hall problem 以推进编码,这就是我尝试将所有内容随机化的原因。问题是:我遇到了一些麻烦。你们中的大多数人可能都知道,蒙蒂问题应该表明,换门的胜率(66%)比留在选定的门(33%)更高。出于某种奇怪的原因,虽然我的模拟显示两种情况下的胜率都是 33%,但我不太确定为什么。
代码如下:
from random import *
def doorPriceRandomizer():
door1 = randint(0,2) #If a door is defined 0, it has a price in it
door2 = randint(0,2) #If a door is defined either 1 or 2, it has a goat in it.
door3 = randint(0,2)
while door2 == door1:
door2 = randint(0,2)
while door3 == door2 or door3 == door1:
door3 = randint(0,2)
return door1,door2,door3 #This random placement generator seems to be working fine.
while True:
loopStart = 0
amountWin = 0
amountLose = 0
try:
loopEnd = int(input("How often would you like to run this simulation: "))
if loopEnd < 0:
raise ValueError
doorChangeUser = int(input("[0] = Do not change door; [1] = Change door: "))
if doorChangeUser not in range(0,2):
raise ValueError
except ValueError:
print("Invalid input. Try again.\n")
else:
while loopStart != loopEnd:
gameDoors = doorPriceRandomizer()
inputUser = randint(0,2)
if doorChangeUser == 0:
if gameDoors[inputUser] == 0:
amountWin += 1
loopStart += 1
else:
amountLose += 1
loopStart += 1
elif doorChangeUser == 1:
ChangeRandom = 0
while gameDoors[ChangeRandom] == gameDoors[inputUser]:
ChangeRandom = randint(0,2)
if gameDoors[ChangeRandom] == 0:
amountWin += 1
loopStart += 1
else:
amountLose += 1
loopStart += 1
print("Win amount: ",amountWin,"\tLose amount: ",amountLose)
我做错了什么?我真的很感激所有的帮助!提前致谢!
【问题讨论】:
-
欢迎来到 SO:请拨打tour 并阅读minimal reproducible example,以增加获得所需帮助的机会。您发布的代码块应遵循minimal reproducible example 中的指南。
-
如果有人感兴趣,我做了这个,我把游戏变成了一个函数,所以你可以在一个循环中运行它无数次来获得几率,你可以只调用没有参数的函数玩它。如果您有空闲时间,请查看这对我来说意义重大:github.com/NoahCristino/montyhall
标签: python python-3.x simulation python-3.6