Skip to content

Instantly share code, notes, and snippets.

@melpomene
Created July 9, 2012 17:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save melpomene/3077712 to your computer and use it in GitHub Desktop.
Save melpomene/3077712 to your computer and use it in GitHub Desktop.
Monty Hall problem
from random import randint
class Game:
def __init__(self):
self.correct = randint(0,2)
def make_guess(self, door):
self.guess = door
def verify(self):
return self.correct == self.guess
def open_donkey(self):
val = randint(0,2)
while val == self.correct or val == self.guess:
val = randint(0,2)
return val
def run(change=False, verbose=False):
g = Game()
p = randint(0,2)
if verbose:
print "Player guessing door nr " + str(p+1)
g.make_guess(p)
d = g.open_donkey()
if verbose:
print "Host opens door nr " + str(d+1) + " to reveal a donkey"
if change:
for i in range(3):
if i != p and i != d:
if verbose:
print "Player switches to " + str(i+1)
g.make_guess(i)
else:
if verbose:
print "Player stays on the same door"
win = g.verify()
if verbose:
if win:
print "Player wins!"
else:
print "Player loose..."
return win
def LoopGame(change=False, nbr_of_games=10000000):
if change:
print "Run game. Change everytime. " + str(nbr_of_games) + " iterations."
else:
print "Run game. Never change. " + str(nbr_of_games) + " iterations."
wins = 0
loses = 0
for n in xrange(nbr_of_games):
result = run(change, False)
if result:
wins += 1
else:
loses += 1
print "Wins: " + str(wins) + " Loses: " + str(loses)
if __name__ == "__main__":
LoopGame(True)
LoopGame(False)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment