Created
February 26, 2024 18:42
-
-
Save Taywee/2ba202b1bf7af40293ecffb01c2ab5f2 to your computer and use it in GitHub Desktop.
Monty Hall Problems
This file contains 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 | |
from enum import Enum, auto, unique | |
@unique | |
class Prize(Enum): | |
CAR = auto() | |
GOAT = auto() | |
results = { | |
Prize.CAR: 0, | |
Prize.GOAT: 0, | |
} | |
doors = [Prize.CAR, Prize.GOAT, Prize.GOAT] | |
for _ in range(1_000_000): | |
random.shuffle(doors) | |
unselected_doors = [0, 1, 2] | |
# Player selects a random door. | |
player_choice = random.choice(unselected_doors) | |
unselected_doors.remove(player_choice) | |
# Monty intentionally choosese a goat door to show the player. | |
monty_hall_choice = next(i for i in unselected_doors if doors[i] is Prize.GOAT) | |
unselected_doors.remove(monty_hall_choice) | |
# Switch to the only remaining door | |
switch_choice = unselected_doors[0] | |
results[doors[switch_choice]] += 1 | |
car = results[Prize.CAR] | |
goat = results[Prize.GOAT] | |
total = car + goat | |
percent = car / total * 100 | |
print(f'{percent:.2f}%') |
This file contains 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 | |
from enum import Enum, auto, unique | |
@unique | |
class Prize(Enum): | |
CAR = auto() | |
GOAT = auto() | |
results = { | |
Prize.CAR: 0, | |
Prize.GOAT: 0, | |
} | |
doors = [Prize.CAR, Prize.GOAT, Prize.GOAT] | |
for _ in range(1_000_000): | |
random.shuffle(doors) | |
unselected_doors = [0, 1, 2] | |
# Player selects a random door. | |
player_choice = random.choice(unselected_doors) | |
unselected_doors.remove(player_choice) | |
# Monty selects one of the remaining doors randomly. | |
monty_hall_choice = random.choice(unselected_doors) | |
unselected_doors.remove(monty_hall_choice) | |
# Skip scenarios where Monty didn't select a goat. | |
if doors[monty_hall_choice] is Prize.CAR: | |
continue | |
# Switch to the only remaining door | |
switch_choice = unselected_doors[0] | |
results[doors[switch_choice]] += 1 | |
car = results[Prize.CAR] | |
goat = results[Prize.GOAT] | |
total = car + goat | |
percent = car / total * 100 | |
print(f'{percent:.2f}%') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment