Skip to content

Instantly share code, notes, and snippets.

@kennethlove
Last active December 10, 2015 06:02
Show Gist options
  • Save kennethlove/ecda7e13ce24b24519f1 to your computer and use it in GitHub Desktop.
Save kennethlove/ecda7e13ce24b24519f1 to your computer and use it in GitHub Desktop.
from __future__ import print_function
from collections import namedtuple
import random
# Create an easy-to-return and easy-to-inspect data
# structure for Game results.
Results = namedtuple('Results', ['won', 'switched'])
class Door(object):
prize = False
opened = False
class Game(object):
chosen_door = None
switched_doors = False
def __init__(self):
self.doors = [
Door(),
Door(),
Door()
]
# Pick a random door and give it a prize
random.choice(self.doors).prize = True
def pick_door(self):
self.chosen_door = random.choice(self.doors)
def open_false_door(self):
# Get the non-chosen doors
available_doors = [door for door in self.doors
if door is not self.chosen_door]
for door in available_doors:
if not door.prize:
# Open the first prizeless door
door.opened = True
break
def switch_doors(self):
available_door = [door for door in self.doors
if door is not self.chosen_door
and not door.opened][0]
if random.randint(0, 1):
# Randomly decide to switch doors
self.switched_doors = True
self.chosen_door = available_door
@classmethod
def play(cls):
game = cls()
game.pick_door()
game.open_false_door()
game.switch_doors()
return Results(game.chosen_door.prize, game.switched_doors)
# Play 1000 runs of the game to get significant numbers
games = [Game.play() for _ in range(1000)]
# Games where the player switched doors and won the prize
won_switched = list(filter(lambda g: g.won and g.switched, games))
# Games where the player did *not* switch doors and won the prize
won_original = list(filter(lambda g: g.won and not g.switched, games))
# Games where the player did *not* switch doors and lost
lost_original = list(filter(lambda g: not g.won and not g.switched, games))
# Games where the player switched doors and lost
lost_switched = list(filter(lambda g: not g.won and g.switched, games))
print("Won and switched:", len(won_switched))
print("Won and didn't switch:", len(won_original))
print("Lost and switched:", len(lost_switched))
print("Lost and didn't switch:", len(lost_original))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment