下面的代码是我的实现(python3.3.1),看看是否可以证明切换在montyhall问题中是有效的。当我让玩家保留他们的第一选择时,我得到了一个大概0.33的正确猜测结果,这是意料之中的。这个问题发生在我换球员的时候-我没有得到预期的~0.66,而是一直得到~0.55。在
有人能看到错误吗?(另外,作为补充说明,如果我能对代码进行任何改进,我将不胜感激)
def runInstance(switch): #run a single Monty Hall Problem instance
choicesList = [False,False,False]
intTruth = randint(0,2)
choicesList[intTruth] = True #list has been set up with 2 False, 1 True
intChoice = randint(0,2)
for index in range(0,len(choicesList)): #Loop finds entry index which is not chosen and is False to "present" to player
if( (intChoice != index) and (choicesList[index] == False) ):
alternate = index
if(switch):
for index in range(0,len(choicesList)): #Loop finds entry index which hasn't been chosen, and isn't the "Opened Door", then switches to it
if( (index != intChoice) and (index != alternate) ):
intChoice = index
return choicesList[intChoice]
def runBatch(inputSize, switch): #Run batch of instances for stats
successCount = 0.0
for index in range(0,int(inputSize)):
if(runInstance(switch)):
successCount += 1.0
print(str(successCount/inputSize))
runBatch(100000.0, True) #Number of instances to run, and boolean indicating whether to switch
以下是一个简短、可读的版本:
将代码更改为:
问题是,有时你会切换到原来的选择。在
换句话说,如果intChoice=2,alternate=1,那么:
正如您所见,您需要休息一下:
为了回答您的问题的第二部分,下面是我的实现:
^{pr2}$(对于Python 3,Python2可能需要一些修改。)
使用set操作代替循环来查找不需要的索引。结果是^{cd1>}ed.
不要假装语言是类型化的,或者它是Java:它不是。
^{cd2>}是什么?是否允许传入^{cd3>}?还是非整数浮点数?让打电话的人来处理。
也不需要在周围留个清单。
相关问题 更多 >
编程相关推荐