Skip to content

Instantly share code, notes, and snippets.



Last active Nov 14, 2018
What would you like to do?
Monty Hall simulation in Python
import random
class Door(object):
def __init__(self, has_car):
self.has_car = has_car
self.selected = False
class Game(object):
def __init__(self):
self.doors = [Door(False), Door(False), Door(True)]
def select_door(self):
# "random" is not an ideal random number generator as:
# a) it's a PRNG, not a true RNG
# b) it's not even cryptographically secure
# ...but it should be a good enough approximation for experiments
self.doors[0].selected = True
def remove_empty(self):
# Remove one that's not selected and doesn't have the car
for door in self.doors:
if (not door.selected) and (not door.has_car):
def switch(self):
# Only 2 entries left, so switch selections
for door in self.doors:
if (door.selected):
door.selected = False
door.selected = True
def has_won(self):
for door in self.doors:
if door.has_car and door.selected:
return True
return False
def play(self, iterations, switch):
# This could probably be written in a more Pythonic way,
# but I wanted to make the steps of the game explicit
games_won = 0
for game in range(0, iterations):
if switch:
if self.has_won():
games_won += 1
return games_won
if __name__ == "__main__":
game = Game()
iterations = 500000
stick_won =, False)
switch_won =, True)
print("Iterations: ", iterations)
print("Stick:", stick_won)
print("Switch: ", switch_won)
print("Ratio (switch / stick): %1.3f" % float(switch_won / stick_won))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.