简体   繁体   中英

Why does this implementation of the Monty Hall give the probability to be 50%?

I recently watched a video about the Monty Hall Problem and was interested in the fact that the contestant had a 2/3 chance of winning when switching. So, I decided to write a simulation for it to see it for myself. However, my simulation gave the answer to be 50%. Could somebody point out why? Note: the number of doors can be adjusted by changing num_of_doors .

from random import randint

num_of_doors = 3
num_of_simulations = 0
wins = 0

while True:
    num_of_simulations += 1
    doors = {k: "Donkey" for k in range(1, num_of_doors + 1)}
    car = randint(1, num_of_doors)
    doors[car] = "Car"
    choice = randint(1, num_of_doors)

    while len(doors) > 2:
        reveal = randint(1, num_of_doors)
        if reveal in doors:
            if reveal != choice and doors[reveal] != "Car":
                del doors[reveal]

    for k in doors:
        if k != choice:
            choice = k

    if doors[choice] == "Car":
        wins += 1
    print(100 * wins / num_of_simulations)

You've found the answer, but I thought I'd just post my shot at this:

from random import randint

def monty(n_doors):
    car = randint(0, n_doors - 1)
    first_choice = 0  # always pick 0 for convenience
    remaining_door = car if first_choice != car else 1  # 1 for convenience
    return remaining_door == car

total_runs = 10000
trials = [monty(3) for x in range(total_runs)]
print(sum(trials) / total_runs)

Gives:

0.6705

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM