Skip to content

Instantly share code, notes, and snippets.

@dwinter
Created April 18, 2011 00:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dwinter/924642 to your computer and use it in GitHub Desktop.
Save dwinter/924642 to your computer and use it in GitHub Desktop.
Code to run simulation of the Monty hall problem
# -*- 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