Created
August 10, 2012 20:14
-
-
Save aaronsw/3317477 to your computer and use it in GitHub Desktop.
Python solution to the Monty Hall problem
This file contains hidden or 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
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