Skip to content

Instantly share code, notes, and snippets.

@well-it-wasnt-me
Created October 6, 2025 13:44
Show Gist options
  • Select an option

  • Save well-it-wasnt-me/e3e0f574ec1a8757bf026796b34edcf1 to your computer and use it in GitHub Desktop.

Select an option

Save well-it-wasnt-me/e3e0f574ec1a8757bf026796b34edcf1 to your computer and use it in GitHub Desktop.
run monty hall simulations to see if is better to switch door or not
import random
def monty_hall_trial(switch: bool) -> bool:
"""
Run a single Monty Hall trial.
Returns True if the player wins the car, False otherwise.
"""
doors = [0, 1, 2]
prize = random.choice(doors) # door hiding the prize
choice = random.choice(doors) # player's initial pick
# Host opens a goat door that's neither the prize nor the player's choice
possible_opens = [d for d in doors if d != prize and d != choice]
opened = random.choice(possible_opens)
# The only remaining closed door that's not the player's initial choice or opened by host
remaining_closed = next(d for d in doors if d != choice and d != opened)
final_choice = remaining_closed if switch else choice
return final_choice == prize
def run_simulations(n_trials: int = 1000):
stay_wins = sum(monty_hall_trial(switch=False) for _ in range(n_trials))
switch_wins = sum(monty_hall_trial(switch=True) for _ in range(n_trials))
stay_rate = stay_wins / n_trials * 100.0
switch_rate = switch_wins / n_trials * 100.0
print(f"Trials: {n_trials}")
print("----- Results -----")
print(f"Stay with original choice: {stay_wins} wins ({stay_rate:.1f}%)")
print(f"Switch door: {switch_wins} wins ({switch_rate:.1f}%)")
if __name__ == "__main__":
run_simulations(1000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment