Skip to content

Instantly share code, notes, and snippets.

@msafadieh
Created March 27, 2019 05:16
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 msafadieh/2d907b8b3bb39c39f6dec18d3b0cb67f to your computer and use it in GitHub Desktop.
Save msafadieh/2d907b8b3bb39c39f6dec18d3b0cb67f to your computer and use it in GitHub Desktop.
simulation of the Monty hall problem
'''
a simulation of the Monty hall problem
'''
from random import choice, sample
TRIALS = 10000
def monty():
'''
runs a simulation of the monty problem. this program will switch
after the goat door is revealed.
:returns 1 if the door with the car was chosen, 0 otherwise.
'''
doors = sample([0, 0, 1], 3)
door = choice(range(3))
goat_door = next(index for index, item in enumerate(doors) if index - door and not item)
return doors[3 - door - goat_door]
def run_loop(trials):
'''
runs the monty problem simulator
:param trials: number of trials
:returns percentage of times the door with car was chosen.
'''
total = sum(monty() for _ in range(trials)) * 100 / trials
return total
if __name__ == "__main__":
print(run_loop(TRIALS))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment