import random
def simulate_n_door_monty_fall(num_doors, num_runs):
if num_doors < 3:
print("You need at least 3 doors for this to be a Monty Hall problem!")
return
stay_wins = 0
switch_wins = 0
monty_opened_car = 0
valid_games = 0
for _ in range(num_runs):
doors = list(range(num_doors))
car_door = random.randint(0, num_doors - 1)
# 1. Player makes an initial choice
player_choice = random.randint(0, num_doors - 1)
# 2. Monty chooses (N - 2) doors at random from the ones NOT chosen by player
available_to_monty = [d for d in doors if d != player_choice]
doors_to_open = random.sample(available_to_monty, num_doors - 2)
if car_door in doors_to_open:
# Result -> Monty accidentally revealed the car
monty_opened_car += 1
else:
valid_games += 1
# Result -> Keep door
if player_choice == car_door:
stay_wins += 1
# Result -> Switch door
remaining_door = [d for d in doors if d != player_choice and d not in doors_to_open][0]
if remaining_door == car_door:
switch_wins += 1
print(f"Results for {num_runs} Runs with {num_doors} Doors")
print(f"Monty opened the car: {monty_opened_car}")
print(f"Valid games (Only goats revealed): {valid_games}")
print("-" * 40)
if valid_games > 0:
print(f"Wins by Staying: {stay_wins} ({(stay_wins/valid_games)*100:.1f}%)")
print(f"Wins by Switching: {switch_wins} ({(switch_wins/valid_games)*100:.1f}%)")
else:
print("Monty opened the car every single time!")
if __name__ == "__main__":
simulate_n_door_monty_fall(num_doors=100, num_runs=10000)Results for 10000 Runs with 100 Doors
Monty opened the car: 9797
Valid games (Only goats revealed): 203
----------------------------------------
Wins by Staying: 97 (47.8%)
Wins by Switching: 106 (52.2%)