Skip to content

Instantly share code, notes, and snippets.

@ddimtirov
Created November 2, 2013 08:19
Show Gist options
  • Save ddimtirov/7276748 to your computer and use it in GitHub Desktop.
Save ddimtirov/7276748 to your computer and use it in GitHub Desktop.
Simulation for the Monty Hall problem in Python, packaged as Windows executable using dist-utils.
import random
class Car: pass
class Sheep: pass
class MontyHall:
cars = 0
sheep = 0
def __init__(self):
carLocation = random.randint(0, 2)
self.doors = range(3)
for i in range(3):
if i==carLocation: self.doors[i]=Car
else: self.doors[i]=Sheep
def reset(cls):
cls.cars = 0
cls.sheep = 0
reset = classmethod(reset)
def pick(self):
self.picked = random.randint(0, 2)
for i in range(3):
if i==self.picked: continue
if self.doors[i]==Car: continue
self.opened=i
break
def change(self):
for i in range(3):
if i==self.picked: continue
if i==self.opened: continue
self.picked=i
break
def check(self):
if self.doors[self.picked]==Car: MontyHall.cars += 1
if self.doors[self.picked]==Sheep: MontyHall.sheep += 1
for i in range(100000):
m = MontyHall()
m.pick()
m.check()
print "No change: Cars=%d; Sheep=%d" % (MontyHall.cars, MontyHall.sheep)
MontyHall.reset()
for i in range(100000):
m = MontyHall()
m.pick()
m.change()
m.check()
print "Change: Cars=%d; Sheep=%d" % (MontyHall.cars, MontyHall.sheep)
#!/usr/bin/env python
from distutils.core import setup
import py2exe
setup(name="MontyHall",
description="Monty Hall Problem",
version="1.0",
py_modules=["monty"],
console=["monty.py"],
windows=[]
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment