Skip to content

Instantly share code, notes, and snippets.

@koorukuroo
Created March 14, 2025 10:20
Show Gist options
  • Save koorukuroo/9ba8681f454c04005355a5ae4e3d6cc1 to your computer and use it in GitHub Desktop.
Save koorukuroo/9ba8681f454c04005355a5ae4e3d6cc1 to your computer and use it in GitHub Desktop.
import random
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import pandas as pd
# Monty Hall simulation function
def monty_hall_simulation(trials=1000, switch=True):
results = []
for _ in range(trials):
prize_door = random.randint(0, 2) # Randomly place the car behind one of the doors
chosen_door = random.randint(0, 2) # Player's initial choice
doors = [0, 1, 2]
# Doors available for Monty to open (excluding player's choice and 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 chooses to switch, select the remaining door
if switch:
chosen_door = [door for door in doors if door != chosen_door and door != monty_door][0]
win = (chosen_door == prize_door) # Determine if the player won
results.append((chosen_door, prize_door, monty_door, win))
return pd.DataFrame(results, columns=['chosen_door', 'prize_door', 'monty_door', 'win'])
# Generate data
trials = 1000
df_switch = monty_hall_simulation(trials=trials, switch=True) # Data for switching strategy
df_stay = monty_hall_simulation(trials=trials, switch=False) # Data for staying strategy
# 1. Analyze the pattern of doors opened by Monty
plt.figure(figsize=(8, 5))
sns.countplot(x=df_switch["monty_door"], palette="coolwarm")
plt.xticks([0, 1, 2], labels=["Door 1", "Door 2", "Door 3"])
plt.xlabel("Door Opened by Monty")
plt.ylabel("Frequency")
plt.title("Monty's Door Choice Distribution")
plt.show()
# 2. Compare player's choice vs car location (Switching strategy)
plt.figure(figsize=(8, 5))
sns.heatmap(pd.crosstab(df_switch["chosen_door"], df_switch["prize_door"]),
annot=True, fmt="d", cmap="YlGnBu")
plt.xlabel("Car Location")
plt.ylabel("Player's Final Choice")
plt.title("Player's Choice vs Car Location (Switch Strategy)")
plt.show()
# 3. Compare player's choice vs car location (Staying strategy)
plt.figure(figsize=(8, 5))
sns.heatmap(pd.crosstab(df_stay["chosen_door"], df_stay["prize_door"]),
annot=True, fmt="d", cmap="OrRd")
plt.xlabel("Car Location")
plt.ylabel("Player's Final Choice")
plt.title("Player's Choice vs Car Location (Stay Strategy)")
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment