Last active
November 14, 2018 11:37
-
-
Save charlienewey/53c8faedc6836e6c42ca to your computer and use it in GitHub Desktop.
Monty Hall simulation in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
random.shuffle(self.doors) | |
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): | |
self.doors.remove(door) | |
def switch(self): | |
# Only 2 entries left, so switch selections | |
for door in self.doors: | |
if (door.selected): | |
door.selected = False | |
else: | |
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): | |
self.__init__() | |
self.select_door() | |
self.remove_empty() | |
if switch: | |
self.switch() | |
if self.has_won(): | |
games_won += 1 | |
return games_won | |
if __name__ == "__main__": | |
game = Game() | |
iterations = 500000 | |
stick_won = game.play(iterations, False) | |
switch_won = game.play(iterations, 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