Skip to content

Instantly share code, notes, and snippets.

@windweller
Created October 9, 2015 23:41
Show Gist options
  • Save windweller/cc871fc02168d3dabe34 to your computer and use it in GitHub Desktop.
Save windweller/cc871fc02168d3dabe34 to your computer and use it in GitHub Desktop.
This python program simulates the simplest Monty Hall 3-door problem. No optimization, but can be easily extended to count for many-door situations.
# Monty Hall simulation
import numpy as np
winningdoor = -1 # ordinal numbers
firstChoice = -1 # both first pick and final pick
closedDoor = -1
finalChoice = -1
# called at every loop to initialize result
def initialize():
"""
This gets an array of 3 elements
then we choose the first as winner, the rest as loser
"""
global firstChoice
global closedDoor
global winningdoor
global finalChoice
firstChoice = -1
closedDoor = -1
winningdoor = -1
finalChoice = -1
choice = np.random.choice(3)
winningdoor = choice
# initial pick
def firstPick():
global firstChoice
firstChoice = np.random.choice(3)
# host closes the door
def hostChoice():
"""
not allowed to close winning door or door first pick is picked
"""
global closedDoor
choices = []
for i in range(0, 3):
if (i != winningdoor) and (i != firstChoice):
choices.append(i)
closedDoor = np.random.choice(choices) # choose a door to close
# switch: true = switch door; false = stay
def finalDecision(switch):
global firstChoice
global finalChoice
if switch:
for i in range(0, 3):
if (i != closedDoor) and (i != firstChoice):
finalChoice = i # pick the other door
else:
finalChoice = firstChoice
# determine who wins by comparing two arrays
def determineWinner():
if finalChoice == winningdoor:
return True
else:
return False
def strategyRun(switch, times):
winningStatistics = 0.0
totalGame = 0.0
for x in range(0, times):
totalGame += 1
initialize()
firstPick()
hostChoice()
finalDecision(switch)
if determineWinner():
winningStatistics += 1
print("total game: " + str(totalGame))
print("winning #: " + str(winningStatistics))
print("prob of winning: " + str(winningStatistics / totalGame))
if __name__ == '__main__':
strategyRun(True, 1000)
strategyRun(False, 1000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment