Skip to content

Instantly share code, notes, and snippets.

@djoreilly
Created February 18, 2025 13:36
Show Gist options
  • Save djoreilly/18b477ff6d5c48ff38424d86d00d32e7 to your computer and use it in GitHub Desktop.
Save djoreilly/18b477ff6d5c48ff38424d86d00d32e7 to your computer and use it in GitHub Desktop.

Revisions

  1. djoreilly created this gist Feb 18, 2025.
    39 changes: 39 additions & 0 deletions monty-hall.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,39 @@
    # monty hall problem simulation https://en.wikipedia.org/wiki/Monty_Hall_problem

    import random

    ITERATIONS = 10000

    stick_count = 0
    stick_wins = 0
    switch_count = 0
    switch_wins = 0

    for _ in range(ITERATIONS):
    doors = ["car", "goat", "goat"]
    random.shuffle(doors)
    car_idx = doors.index("car")

    # pick a random index into list doors. List indexes start at 0 and stop at len(doors)-1
    pick_idx = random.randint(0, 2) # 0, 1 or 2

    reveal_candidates = [0, 1, 2]
    reveal_candidates.remove(pick_idx)
    if car_idx != pick_idx:
    reveal_candidates.remove(car_idx)
    reveal_idx = random.choice(reveal_candidates)

    if random.choice(["stick", "switch"]) == "stick":
    stick_count += 1
    if pick_idx == car_idx:
    stick_wins += 1
    else:
    switch_count += 1
    if pick_idx != car_idx:
    switch_wins += 1


    stick_win_pc = stick_wins / stick_count * 100
    print(f"stick win percentage: {stick_wins}/{stick_count} = {stick_win_pc:.2f}%")
    switch_win_pc = switch_wins / switch_count * 100
    print(f"switch win percentage: {switch_wins}/{switch_count} = {switch_win_pc:.2f}%")
    5 changes: 5 additions & 0 deletions run.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,5 @@
    ```
    $ python3 monty-hall.py
    stick win percentage: 1610/4975 = 32.36%
    switch win percentage: 3271/5025 = 65.09%
    ```