Skip to content

Instantly share code, notes, and snippets.

@ryansturmer
Created January 18, 2021 04:43
Show Gist options
  • Save ryansturmer/1658b87b86e5083cf352857da6b1281e to your computer and use it in GitHub Desktop.
Save ryansturmer/1658b87b86e5083cf352857da6b1281e to your computer and use it in GitHub Desktop.
Monty Hall Problem
# Monty Hall Problem Simulation
# Author: Ryan Sturmer
#
import random
def play_round(doors, switch):
# Choose the location of the car
car = random.randint(1, doors)
# Contestant chooses a door
initial_choice = random.randint(1, doors)
# Monty opens ALL the other doors except one
if initial_choice != car:
monty_leaves = car # If the car wasn't chosen, Monty is forced to reveal its location
else:
while True:
monty_leaves = random.randint(1, doors)
if monty_leaves != initial_choice:
break
# monty_leaves is now the door that Monty DIDN'T open
if switch:
final_choice = monty_leaves
else:
final_choice = initial_choice
victory = (final_choice == car)
return victory, initial_choice, final_choice, car
def simulation(iterations, doors=3):
games_won_switch = 0
games_won_noswitch = 0
games_won_random = 0
for i in range(iterations):
won_game, intial_choice, final_choice, car = play_round(doors, False)
if(won_game):
games_won_noswitch += 1
won_game, intial_choice, final_choice, car = play_round(doors, True)
if(won_game):
games_won_switch += 1
won_game, initial_choice, final_choice, car = play_round(doors, random.choice([False, True]))
if(won_game):
games_won_random += 1
print("")
print(" Monty Hall Simulation")
print("---------------------------------------------")
print(" Iterations: %d" % iterations)
print(" Games won when switching doors: %d (%g%%)" % (games_won_switch, 100*float(games_won_switch)/float(iterations)))
print("Games won when NOT switching doors: %d (%g%%)" % (games_won_noswitch, 100*float(games_won_noswitch)/float(iterations)))
print("Games won when random switching doors: %d (%g%%)" % (games_won_random, 100*float(games_won_random)/float(iterations)))
if __name__ == '__main__':
simulation(100000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment