Monty Hall Python 模拟计算



我试图模拟蒙蒂霍尔问题,有人选择一扇门,然后随机删除一扇门——最后它必须是有车的门和没有车的门,其中一扇必须有人选择。虽然我目前不需要模拟/询问使用该程序的人他们想要哪扇门,但我在实际设置计算时遇到了麻烦。当我运行代码时,它输出 0,其中 is 应该大约是 66%

import random
doors=[0,1,2]
wins=0
car=random.randint(0,2)
player=random.randint(0,2)
#This chooses the random door removed
if player==car:
    doors.remove.random.randint(0,2)
else:
    doors.remove(car)
    doors.remove(player)
for plays in range(100):
    if car == player:
        wins=wins+1
print(wins) 

您需要将代码放在循环中才能每次实际运行。 您还需要确保只允许第二次有效选择(他们不能选择移除的门),并且您只移除有效的门(您不能移除带有汽车的门或玩家选择的门)。

import random
wins = 0
for plays in range(100):
    doors = [0,1,2]
    car = random.choice(doors)
    player = random.choice(doors)
    # This chooses the random door removed
    doors.remove(random.choice([d for d in doors if d != car and d != player]))
    # Player chooses again (stay or switch)
    player = random.choice(doors)
    if player == car:
        wins += 1
print(wins)

但是对于Monty Hall问题,你甚至不必跟踪门。

win_if_stay = 0
win_if_switch = 0
for i in range(100):
    player = random.randint(0, 2)
    car = random.randint(0, 2)
    if player == car:
        win_if_stay += 1
    else:
        win_if_switch += 1

最新更新