Created
April 18, 2011 00:38
-
-
Save dwinter/924642 to your computer and use it in GitHub Desktop.
Code to run simulation of 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
# -*- coding: utf-8 -*- | |
import random | |
def round(switch=True): | |
doors = ['car', 'goat', 'goat'] | |
pick = random.randrange(3) | |
print "the RNG picked door %s" % (pick + 1) | |
#monty knows where the car is | |
car = doors.index('car') | |
#and he opens a door without the car | |
monty_shows = random.choice([i for i in range(3) if i not in [pick, car]]) | |
print "Monty opens door %s and reveals a goat!" % (monty_shows + 1) | |
if switch: | |
pick = [i for i in range(3) if i not in [pick, monty_shows]][0] | |
print "the RNG switched to door %s" % (pick + 1) | |
if pick== car: | |
return 1 | |
else: | |
return 0 | |
def simulation(handle, generations=1000): | |
switch = 0 | |
stay = 0 | |
for gen in range(generations): | |
switch += round(switch=True) | |
stay += round(switch= False) | |
handle.write("%s,%s\n" % (switch/(gen + 1.0), stay/(gen + 1.0))) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment