Monty Hall Problem Simulation
"""
This is a simulation of Monty Hall Problem.
https://en.wikipedia.org/wiki/Monty_Hall_problem
Suppose you're on a game show, and you're given the choice of three doors: Behind one door is a car; behind the others, goats.
You pick a door, say No. 1, and the host, who knows what's behind the doors, opens another door, say No. 3, which has a goat.
He then says to you, "Do you want to pick door No. 2?" Is it to your advantage to switch your choice?
"""
import random
NUM_DOORS = 3 # three doors in the game
MAX_ROUND = 10000 # number of rounds for statistics
change_win_count = 0
for _ in range(MAX_ROUND):
# randomly to put a car behind a door
car_door = random.randint(0, NUM_DOORS - 1)
# the player firstly selects a door
player_first_guess = random.randint(0, NUM_DOORS - 1)
# the host opens another door without a car
host_door = random.choice([
x for x in range(NUM_DOORS) if x != player_first_guess and x != car_door
])
# the option if the player changes his mind
player_second_guess = random.choice([
x for x in range(NUM_DOORS) if x != player_first_guess and x != host_door
])
# count the win if the second guess is correct
if player_second_guess == car_door:
change_win_count += 1
# Print the statistics result
print("Win percentage if you switch the choice is {r:.2f}%".format(
r=(change_win_count * 100) / MAX_ROUND))
Comments