我的python-Monty-hall模拟有什么问题吗?

2024-06-02 05:36:14 发布

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

我哪里出错了吗?即使在换人之后,我也能得到50%的胜利。你知道吗

import random

def monty_hall():

    #-----setup ----#

    prizes = ["Car" , "Goat" , "Goat"]
    random.shuffle(prizes)

    #----person chooses at random----#

    choose_index = random.randint(0,2)

    ##-------host reveals a goat------#

    while True:
        goat_gate = random.randint(0, 2)
        if prizes[goat_gate] == "Goat":
            break

    ##------person switches -------##

    while True:
        switch_choice = random.randint(0, 2)
        if (switch_choice!= choose_index) & (switch_choice!= goat_gate):
            break

    ## -- check if won---#

    if prizes[switch_choice] == "Car":
        return True

win = 0
games = 100000

for times in range(games):
    if monty_hall() == True:
        win += 1

print(win/games)

Tags: trueifrandomcarwingamesrandintchoice
1条回答
网友
1楼 · 发布于 2024-06-02 05:36:14

是的,你没有包括这样一个事实:主人不会透露所选门后面的东西。你知道吗

while True :
    goat_gate = random.randint(0, 2)
    if prizes[goat_gate] == "Goat" :
        break

应该是

while True :
    goat_gate = random.randint(0, 2)
    if prizes[goat_gate] == "Goat" and goat_gate != choose_index:
        break

相关问题 更多 >