首页 > 解决方案 > Monty Hall 模拟器无法正常工作

问题描述

我试图模拟蒙蒂霍尔问题。

首先,我选择了获胜的门并随机选择了一个选项。然后打开一扇不是所选门的门。然后检查是否选中 = 获胜门。如果是,我将 1 添加到不切换点 (b.num)。

然后切换选择,我从门列表中删除了选定的门,并将选择均衡到列表中的唯一项目。然后检查是否选中 = 再次获胜门,如果是,我将 1 添加到切换点 (s.num1)。

问题是切换获胜百分比大致等于 33。它的预期值约为 66。问题出在哪里?

import random
from random import randint

def b():
    b.num+=1
b.num=0

def s():
    s.num+=1
s.num=0

d=int(input("try count: "))

def a():
    winner=randint(1,3)
    selection=randint(1,3)
    doors=[1,2,3]
    doors_to_open=randint(1,2)
    if selection == 1:
        if doors_to_open==1:
            doors.remove(2)
        else:
            doors.remove(3)

    if selection == 2:
        if doors_to_open==1:
            doors.remove(1)
        else:
            doors.remove(3)

    if selection == 3:
        if doors_to_open==1:
            doors.remove(1)
        else:
            doors.remove(2)

    if selection == winner:
        b()
        #print("Not switching win count: ",b.num)

    # switch

    doors.remove(selection)
    selection = doors[0]

    if selection == winner:
        s()
        #print("Switching win count: ",s.num)

for q in range (0,d):
    a()

#print("Switching win count: ",s.num)
print("Switching percent: ",(s.num/d)*100)
#print("Not switching win count: ",b.num)
print("Not switching percent: ",(b.num/d)*100)

input()

标签: python

解决方案


您在调用 s 函数时错过了不等于运算符。如果你添加!在条件。它将修复您的模拟。

import random
from random import randint

def b():
    b.num+=1
b.num=0

def s():
    s.num+=1
s.num=0

d=int(input("try count: "))

def a():
    winner=randint(1,3)
    selection=randint(1,3)
    doors=[1,2,3]
    doors_to_open=randint(1,2)
    if selection == 1:
        if doors_to_open==1:
            doors.remove(2)
        else:
            doors.remove(3)

    if selection == 2:
        if doors_to_open==1:
            doors.remove(1)
        else:
            doors.remove(3)

    if selection == 3:
        if doors_to_open==1:
            doors.remove(1)
        else:
            doors.remove(2)

    if selection == winner:
        b()
        #print("Not switching win count: ",b.num)

    # switch

    doors.remove(selection)
    selection = doors[0]

    if selection != winner: #Change is done in this line
        s()
        #print("Switching win count: ",s.num)

for q in range (0,d):
    a()

#print("Switching win count: ",s.num)
print("Switching percent: ",(s.num/d)*100)
#print("Not switching win count: ",b.num)
print("Not switching percent: ",(b.num/d)*100)

推荐阅读