Sunday, February 8, 2009

Monty Hall Problem (Python Style)

Okay, now for the python formulation of the Monty Hall Problem.
#!/usr/bin/env python
import random # import python library random
random.seed() # seed random number generator

def letsMakeADeal(nDoors, switch):
"""Simulate Monty Hall Problem of Lets Make a Deal
Inputs:
nDoors - integer number of doors
switch - switch (True) or stay (False)
Return:
Win (True) or loose (False)"""
prizeDoor = random.randint(1,nDoors) # car is behind a random door
playerDoor = random.randint(1,nDoors) # player chooses random door

if playerDoor == prizeDoor: # If player selects prize door and...
if switch: win = False # player switches, then player loses
else: win = True # player stays, then player wins
if playerDoor != prizeDoor: # If player doesn't select prize door and...
if switch: win = True # player switches, then player wins
else: win = False # player stays, then player looses
return win # return if the player wins (True)
# or looses (False)

nTrials = 1000 # set number of trials
nDoors = 3 # set number of doors
swWins = 0 # initial number of switch wins
stWins = 0 # initial number of stay wins

for i in range(nTrials): # run nTrials number of trials
# run simulation assuming that you will switch doors
if letsMakeADeal(nDoors=nDoors, switch=True): # if switch wins
swWins = swWins + 1 # increment the number of switch wins by one
# run simulation assuming that you will not switch doors
if letsMakeADeal(nDoors=nDoors, switch=False): # if stay wins
stWins = stWins + 1 # increment the number of stay wins by one

swWinPcnt = swWins/float(nTrials)*100 # calculate swich win percent
stWinPcnt = stWins/float(nTrials)*100 # calculate stay win percent

print "Switch Wins %%: %0.2f" % (swWinPcnt)
print "Stay Wins %%: %0.2f" % (stWinPcnt)
The output from this prints the win percentage for staying and the win percentage for switching after doing a thousand trials of each. Some sample outputs are:
Switch Wins %: 65.60
Stay Wins %: 34.40
>>>
Switch Wins %: 65.70
Stay Wins %: 35.10
>>>
Switch Wins %: 68.30
Stay Wins %: 35.30
>>>
Your mileage may vary depending on the number of trails you run and the number of doors. Of course, changing the number of doors changes the probability accordingly. If you have 4 doors, there is a 75% chance you will win if you switch and only a 25% chance you will win if you stay. This is reflected by modifying the number of doors (nDoors) in the program and rerunning:
Switch Wins %: 73.70
Stay Wins %: 26.40
>>>
So there you have it folks, a python program that calculates your chances of winning Lets Make a Deal.

3 comments:

  1. omg you actually commented your code; hell has officially frozen over.

    ReplyDelete
  2. well, for once i thought someone would actually be looking at my code

    ReplyDelete
  3. I've been trying to explain this concept to people, but I'm horrible at speaking math. Thanks, Sparky!

    ReplyDelete