Skip to content

Instantly share code, notes, and snippets.

@Taywee
Created February 26, 2024 18:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Taywee/2ba202b1bf7af40293ecffb01c2ab5f2 to your computer and use it in GitHub Desktop.
Save Taywee/2ba202b1bf7af40293ecffb01c2ab5f2 to your computer and use it in GitHub Desktop.
Monty Hall Problems
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}%')
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