Skip to content

Instantly share code, notes, and snippets.

@koorukuroo
Created March 14, 2025 10:12
Show Gist options
  • Save koorukuroo/15b29c41839ae69c689b100b38a2a3cb to your computer and use it in GitHub Desktop.
Save koorukuroo/15b29c41839ae69c689b100b38a2a3cb to your computer and use it in GitHub Desktop.
import random
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
# Monty Hall simulation function
def monty_hall(switch=True):
prize_door = random.randint(0, 2) # Randomly assign the prize behind one of the three doors
chosen_door = random.randint(0, 2) # Player's initial choice of door
doors = [0, 1, 2]
# Host selects a door to open (excluding the player's choice and the prize door)
available_doors = [door for door in doors if door != chosen_door and door != prize_door]
monty_door = random.choice(available_doors)
# If the player decides to switch, choose the remaining unopened door
if switch:
chosen_door = [door for door in doors if door != chosen_door and door != monty_door][0]
return chosen_door == prize_door # Return whether the player won the prize
# Run the simulation
trials = 100
switch_wins = [monty_hall(switch=True) for _ in range(trials)]
stay_wins = [monty_hall(switch=False) for _ in range(trials)]
# 1. Bar plot comparing win probabilities
plt.figure(figsize=(8, 5))
sns.barplot(x=['Stay', 'Switch'], y=[sum(stay_wins) / trials, sum(switch_wins) / trials], palette=['red', 'blue'])
plt.ylim(0, 1)
plt.ylabel('Winning Probability')
plt.title('Winning Probability: Stay vs Switch')
plt.show()
# 2. Line plot showing probability convergence over increasing trials
cumulative_switch_wins = np.cumsum(switch_wins) / np.arange(1, trials + 1)
cumulative_stay_wins = np.cumsum(stay_wins) / np.arange(1, trials + 1)
plt.figure(figsize=(10, 5))
plt.plot(cumulative_switch_wins, label="Switching Strategy", color="blue")
plt.plot(cumulative_stay_wins, label="Staying Strategy", color="red")
plt.axhline(y=2/3, color='blue', linestyle='--', label="Expected 66.7% (Switch)")
plt.axhline(y=1/3, color='red', linestyle='--', label="Expected 33.3% (Stay)")
plt.xlabel("Number of Trials")
plt.ylabel("Winning Probability")
plt.title("Winning Probability Convergence Over Trials")
plt.legend()
plt.show()
# 3. Scatter plot showing individual experiment outcomes
plt.figure(figsize=(12, 5))
plt.scatter(range(trials), switch_wins, color='blue', alpha=0.5, label="Switch Wins (1=Win, 0=Loss)")
plt.scatter(range(trials), stay_wins, color='red', alpha=0.5, label="Stay Wins (1=Win, 0=Loss)")
plt.xlabel("Trial Number")
plt.ylabel("Win (1) / Loss (0)")
plt.title("Individual Experiment Outcomes")
plt.legend()
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment