为什么我的蒙蒂霍尔解决方案不起作用?

2024-10-02 02:24:29 发布

您现在位置:Python中文网/ 问答频道 /正文

下面的代码是我的实现(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

Tags: andto代码infalsetrueforindex
3条回答

以下是一个简短、可读的版本:

def mh(trials=1000):
    kept, switched = 0, 0
    for trial in range(trials):
        behind_curtains = ['goat', 'goat', 'boat']
        shuffle(behind_curtains)
        kept += behind_curtains.pop() is 'boat'
        behind_curtains.remove('goat')
        switched += behind_curtains[0] is 'boat'
    print ('Keeping 1st choice won {} times. \n'
           'Switching choice won {} times').format(kept, switched)

将代码更改为:

origChoice = intChoice
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 != origChoice) and (index != alternate) ):
            intChoice = index

问题是,有时你会切换到原来的选择。在

换句话说,如果intChoice=2,alternate=1,那么:

  1. 在第一次交互时,intChoice将变为0
  2. 在第二次迭代中什么也不会发生(因为index==alternate)
  3. 在第三次迭代中,intChoice将变回2

正如您所见,您需要休息一下:

    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
                break

为了回答您的问题的第二部分,下面是我的实现:

^{pr2}$

(对于Python 3,Python2可能需要一些修改。)

  • 使用set操作代替循环来查找不需要的索引。结果是^{cd1>}ed.

  • 不要假装语言是类型化的,或者它是Java:它不是。

  • ^{cd2>}是什么?是否允许传入^{cd3>}?还是非整数浮点数?让打电话的人来处理。

  • 也不需要在周围留个清单。

相关问题 更多 >

    热门问题