# Monty Hall Simulation

Python Puzzles

Back to the Python! homepage

Run a simulation of the Monty Hall problem.

``````Probability of winning if you switch: 0.666391
Probability of winning if you don't switch: 0.333692``````
```import random

def monty_hall(simulations=100000, switch=True):
win_count = 0

for _ in range(simulations):
doors = [0, 0, 1]  # 0 represents a goat, 1 represents a car
random.shuffle(doors)  # the car is randomly placed

# Contestant's initial choice
initial_choice = random.choice([0, 1, 2])

# Monty opens a door
monty_choice = [i for i in range(3) if i != initial_choice and doors[i] != 1][0]

# Contestant's final choice (switch or don't switch)
final_choice = (set([0, 1, 2]) - set([initial_choice, monty_choice])).pop() if switch else initial_choice

if doors[final_choice] == 1:
win_count += 1

return win_count / simulations

# Run the simulations
print("Probability of winning if you switch:", monty_hall(simulations=1000000, switch=True))
print("Probability of winning if you don't switch:", monty_hall(simulations=1000000, switch=False))
```