thinkpad20

The Monty Hall Problem

Apr 20th, 2012
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.09 KB | None | 0 0
  1. import random
  2.  
  3. def monty (numTrials):
  4.     resultSwitch = 0
  5.     resultStay = 0
  6.     choices = ["Car", "Goat", "Goat"]
  7.     for trial in range(numTrials):
  8.         random.shuffle(choices)
  9.         resultSwitch, resultStay = montyPick(choices,resultSwitch, resultStay)
  10.     print "Out of %d trials run:" % numTrials
  11.     print "Trials won by switching:", resultSwitch, "percent of total:", float(resultSwitch)*100/numTrials
  12.     print "Trials won by staying:", resultStay, "percent of total:", float(resultStay)*100/numTrials
  13.  
  14. def findInList(lst, target):
  15.     for index in range(len(lst)):
  16.         if lst[index] == target:
  17.             return index
  18.     return -1
  19.  
  20. def montyPick (choices, resultSwitch, resultStay):
  21.     pick = 0
  22.     if choices[pick] == "Car": monty = 1
  23.     else: monty = findInList(choices[1:], "Goat") + 1
  24.     if monty == 1: remainingDoor = 2
  25.     else: remainingDoor = 1
  26.     montyChoice = choices[monty]
  27.     if choices[remainingDoor] == "Car":
  28.         resultSwitch += 1
  29.     elif choices[pick] == "Car":
  30.         resultStay += 1
  31.     return resultSwitch, resultStay
  32.  
  33. monty (100000)
Advertisement
Add Comment
Please, Sign In to add comment