【问题标题】:Monty Hall Python Simulation CalculationMonty Hall Python 模拟计算
【发布时间】:2016-03-22 00:33:48
【问题描述】:

我正在尝试模拟蒙蒂霍尔问题,其中有人选择了一扇门,然后随机移除一扇门——最终它一定是有车的,而没有车的,其中一个肯定是有人选择的。虽然我不需要模拟当前/询问使用程序的人他们想要哪个门,但我在实际设置计算时遇到了麻烦。当我运行代码时,它输出 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) 

【问题讨论】:

  • carplayer 在 for 循环内不会改变。您正在比较相同的两个数字 100 次。
  • 如何更改循环内的变量?
  • 将更改它们的代码放在for 语句下...

标签: python simulation


【解决方案1】:

您需要将代码放入循环中才能真正让它每次运行。您还需要确保您第二次只允许有效选择(他们不能选择已移除的门)并且您只移除有效的门(您不能用汽车或玩家移除门-选择的门)。

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)

但就蒙蒂霍尔问题而言,您甚至不必跟踪门。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-15
    相关资源
    最近更新 更多