Skip to content

Instantly share code, notes, and snippets.

@runsun
Created March 14, 2018 17:05
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 runsun/e753e4b65d73cb4d58d6f65126edfa84 to your computer and use it in GitHub Desktop.
Save runsun/e753e4b65d73cb4d58d6f65126edfa84 to your computer and use it in GitHub Desktop.
Monty Hall Problem Simulation
## Monty Hall Problem
## https://en.wikipedia.org/wiki/Monty_Hall_problem
##
## A simulation intended to prove the Monty Hall Solution wrong
## (that switching selection after one door is revealed increases
## the odd from 1/3 to 2/3), ended up proving it right.
##
## Result of running run(1000) 100 times: 0.67(+-)0.02
##
import random, statistics
def monty():
car = random.choice([0,1,2])
pick = random.choice([0,1,2])
no_car = [0,1,2]
no_car.remove(car)
if car==pick: ## if car==pick, randomly remove one of the other 2
remove= random.choice( no_car )
else: ## Otherwise, remove the one neither car nor pick
remove = no_car
remove.remove(pick)
remove=remove[0]
remain = [0,1,2]
remain.remove(remove) ## The remaining 2 after one door is revealed
switchpick = remain
switchpick.remove(pick)
return [car, pick, remove, switchpick[0]]
def run(n=1000):
runs = [ monty() for i in range(n) ]
switched = [ (car==switchpick and 1) or 0 for car,pick,remove,switchpick in runs ]
unswitched = [ (car==pick and 1) or 0 for car,pick,remove,switchpick in runs ]
#return sum(unswitched)/n
return sum(switched)/n
## Test run(1000) k times
k = 100
result = [ run() for i in range(k)]
print( "{:.2f}(+-){:.2f}".format(sum(result)/k, statistics.stdev( result) ))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment