Skip to content

Instantly share code, notes, and snippets.

@Kibouo
Created May 15, 2021 13:32
Show Gist options
  • Save Kibouo/2e520750670137c47be8511c7ca48563 to your computer and use it in GitHub Desktop.
Save Kibouo/2e520750670137c47be8511c7ca48563 to your computer and use it in GitHub Desktop.
Monty Hall simulation
import random
random.seed(1234)
def indicate_choice(doors, choice):
return list(map(lambda tup: tup[1].upper() if tup[0] == choice else tup[1], enumerate(doors)))
GOAT = "goat"
CAR = "car"
OPEN = "open"
AMT_DOORS = 3
AMT_ROUNDS = 1000000
SWITCH = True
print("Config:", f"doors: {AMT_DOORS}", f"round: {AMT_ROUNDS}", f"switch: {SWITCH}", sep="\n- ")
amt_wins = 0
for i in range(AMT_ROUNDS):
print("-" * 10 + f" Round {i} " + "-" * 10)
doors = [GOAT for _ in range(AMT_DOORS)]
doors[random.randrange(AMT_DOORS)] = CAR
choice = random.randrange(AMT_DOORS)
print(f"Initial doors: {indicate_choice(doors, choice)}")
i = 0
while (len(list(filter(lambda door: door != OPEN, doors))) > 2):
if doors[i] == GOAT and i != choice:
doors[i] = OPEN
i += 1
print(f"After opening: {indicate_choice(doors, choice)}")
won = doors[choice] == CAR if not SWITCH else doors[choice] != CAR
amt_wins = amt_wins + 1 if won else amt_wins
print("Win!" if won else "Lost!")
print("-" * 30)
print(f"Won {amt_wins}/{AMT_ROUNDS} (~{amt_wins/AMT_ROUNDS*100}%) of times after", "" if SWITCH else "not", "switching.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment