Skip to content

Instantly share code, notes, and snippets.

@aaronsw
Created August 10, 2012 20:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save aaronsw/3317477 to your computer and use it in GitHub Desktop.
Save aaronsw/3317477 to your computer and use it in GitHub Desktop.
Python solution to the Monty Hall problem
import random
DOORS = (1,2,3)
def hallpicker(strategy):
prize = random.choice(DOORS)
firstchoice = random.choice(DOORS)
if strategy == 'stay':
return firstchoice == prize
elif strategy == 'switch':
hostchoice = random.choice([x for x in DOORS if x != firstchoice and x != prize])
secondchoice = [x for x in DOORS if x != firstchoice and x != hostchoice]
assert len(secondchoice) == 1
return secondchoice[0] == prize
else:
raise ValueError
def counter(strategy, n=10000):
return sum(hallpicker(strategy) for i in xrange(n))/float(n)
if __name__ == "__main__":
print "stay:", counter('stay')
print "switch:", counter('switch')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment