Created
April 3, 2024 23:05
-
-
Save john-science/75a7475ac2e05e3bf36c4837dbd14051 to your computer and use it in GitHub Desktop.
Let's solve the Monty Hall problem using Monte Carlo!
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
""" | |
Modeling the Monty Hall Problem | |
https://en.wikipedia.org/wiki/Monty_Hall_problem | |
Suppose you're on a game show, and you're | |
given the choice of three doors: Behind one | |
door is a car; behind the others, goats. You | |
pick a door, say No. 1, and the host, who | |
knows what's behind the doors, opens another | |
door, say No. 3, which has a goat. He then | |
says to you, "Do you want to pick door No. 2?" | |
Is it to your advantage to switch your choice? | |
Let's solve the Monty Hall problem using Monte Carlo! | |
https://en.wikipedia.org/wiki/Monte_Carlo_method | |
""" | |
from random import randint | |
def main(): | |
n = 10000 | |
print(f"\nIf you play the Monte Hall game {n} times") | |
print(f"{monty_hall_monte_carlo(n, False)}% of the time you win if you don't switch,") | |
print(f"{monty_hall_monte_carlo(n, True)}% of the time you win if you switch.\n") | |
def monty_hall_monte_carlo(n, switch=True): | |
"""Let's solve the Monty Hall problem with Monte Carlo! | |
Parameters | |
---------- | |
n : int | |
How many times should we play the game? | |
switch : bool (defaults True) | |
Should we switch or keep our first guess? | |
Returns | |
------- | |
What percentage of the N times did we win? | |
""" | |
successes = 0 | |
# Let's play the Monty Hall game N times | |
for _ in range(n): | |
# We will set up 3 doors, with one random winner. | |
doors = [0, 0, 0] | |
doors[randint(0, 2)] = 1 | |
# You pick one door at random. | |
your_pick = randint(0, 2) | |
# Every time, you either keep your first guess, or switch. | |
if switch: | |
# If you DO switch... | |
if doors[your_pick] == 1: | |
# If your first guess was correct, you lose. | |
continue | |
else: | |
# If your first guess was wrong, you win. | |
successes += 1 | |
else: | |
# If you don't switch, we just test your first guess. | |
if doors[your_pick] == 1: | |
successes += 1 | |
# return the percentage of times you succeeded | |
return 100 * float(successes) / n | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment