Created
October 6, 2025 13:44
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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