Skip to content

Instantly share code, notes, and snippets.

@chunhualiao
Last active December 26, 2023 19:03
Show Gist options
  • Save chunhualiao/7414823865d0d57387289dc085566c00 to your computer and use it in GitHub Desktop.
Save chunhualiao/7414823865d0d57387289dc085566c00 to your computer and use it in GitHub Desktop.
Simulating the Monty Hall Problem

The Monty Hall Problem (Where is the goat) is fascinating: You are presented with three doors. Behind one door is a car, and behind the other two doors are goats. You choose one of the three doors (hoping it has a car behind it you can win it), but it remains closed for now.

I have asked gpt-4 to create a python problem to simulate the choices and compare their winning rates.

import random

# input parameter: switch or not: true or false
def play_game(switch_doors):
    doors = [0, 0, 1]  # Two goats (0) and one car (1)
    random.shuffle(doors)  # The prizes behind the doors are randomly shuffled
    
    # The player chooses a door (we'll just choose the first one, since it's a random choice it doesn't matter which one we choose)
    chosen_door = doors[0]
    
    # The game host opens one of the other doors, that has a goat behind it (0)
    # So we remove a door that the player didn't choose and that has a goat behind it
    doors.remove(0)
    
    # now only two doors remain
    # If the player decides to switch doors, their choice becomes the other unopened door
    if switch_doors:
        doors.remove(chosen_door)  # now only one door remain and choosen after switching/removing
        chosen_door = doors[0]

    # if no switching, the chosen door is kept intact
    # if the chosen door has a car behind it (1), the player wins
    return chosen_door == 1

def simulate_games(num_games):
    wins_when_switching = 0
    wins_when_not_switching = 0

    for _ in range(num_games):
        if play_game(True):
            wins_when_switching += 1
        if play_game(False):
            wins_when_not_switching += 1

    print(f"Win percentage when switching: {wins_when_switching/num_games * 100}")
    print(f"Win percentage when not switching: {wins_when_not_switching/num_games * 100}")

simulate_games(10000)

Win percentage when switching: 66.47999999999999

Win percentage when not switching: 33.379999999999995

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment