[Python] Monty Hall Dilemma and its simulation

Let's make a deal, 1968

Let’s make a deal, 1968. ABC Photo Archives, via Getty Images.


Imagine a game show where you’re presented with three doors: behind one lies a dream prize, while the others hide consolation gifts. You pick a door, but before the reveal, the host, with full knowledge of what’s behind each door, opens another door, always showing you an item with less value than the main prize. Now, he offers you a chance to switch your choice to the remaining unopened door. Should you stick with your initial pick or take the gamble?

This thought-provoking scenario, known as the Monty Hall problem, has baffled minds for decades. Surprisingly, switching doors actually doubles your chances of winning the prize! This counterintuitive solution stems from the fact that by revealing a goat, the host essentially concentrates all the “losing potential” into one door, leaving the remaining unopened door with a higher probability of holding the treasure. So, next time you face a similar dilemma, remember, sometimes a change of heart can lead to a fortunate outcome!


Here you will find more information about this puzzle:



And here is the code you need to simulate it in Python:

# Youtube.com/@codedabacus
# Monty Hall Problem

# Libraries
import random

# total games
n = 100_000

# list of all possible values
values = ["Car", "X", "X"]

# initialize counters
stay, switch = 0, 0

# generate the games
for _ in range(n):
  # 1. prepare the doors (not the band)
  doors = random.sample(values, 3)

  # 2. what the contestant chooses
  c = random.choice(doors)

  # 3. remove an "X"

  # 4. Check
  if c == "Car":
    stay += 1
    switch += 1

# print the results
print(f"Staying would win %{round((stay/n) * 100, 2)} of the games.")
print(f"Switching would win %{round((switch/n) * 100, 2)} of the games.")



Related Images: