我正在尝试模拟Monty Hall问题,其中有人选择了一扇门,并且随机移除了一扇门 - 最后它必须是一辆有车和一辆没有,其中一人必须选择。虽然我现在不需要模拟/询问使用该程序的人他们想要哪个门,但我实际上在设置计算时遇到了麻烦。当我运行代码时,它输出0,其中应该是大约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)
答案 0 :(得分:2)
您需要将代码放在循环中以实际让它每次运行。您还需要确保您第二次只允许有效选择(他们不能选择拆除的门)并且您只是移除有效的门(您无法将车门或播放器移开 - 选择的门)。
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