Wednesday, July 30, 2008

monty hall

The other day I was introduced to the Monty Hall problem. I had never heard it before and my first guess at the answer was wrong. After some thought (and some reading), it's obvious to me why I was wrong. Being a geek, I wanted to prove it myself with code so I wrote a quick Python class to model the problem.

import random

class Monty:
"The Monty Hall problem"

def __init__(self):
print "init"
iterations = 100
# keep track of how often the keepers and changers win
countKeepers = 0
countChangers = 0
for i in range(iterations):
countKeepers += self.doit(1)
countChangers += self.doit(0)
print "of the %s iterations, the keepers won %s and the changers won %s" % (iterations, countKeepers, countChangers)

def doit(self, keepSelection):
print random.randrange(1,4)
# setup the doors
doors = [0,0,0,0]
# pick one for the car
doorWithCar = random.randrange(1,4)
print "door %s has the car" % doorWithCar
doors[doorWithCar] = 1
# pick one as a contestant
userChoice = random.randrange(1,4)
print "the user chose door", userChoice
# if the contestant is a keeper, then we can stop here
if (keepSelection):
if (userChoice == doorWithCar):
return 1
else:
return 0

# reveal a door
for i in range(1,4):
if (i != userChoice and doors[i] == 0):
revealedDoor = i
print "revealing that door %s has a goat behind it" % revealedDoor
break

# determine if the contestant wins when they change their selection
if (userChoice != doorWithCar):
return 1
else:
return 0

m = Monty()

No comments: