Skip to content

Instantly share code, notes, and snippets.

@kdungs
Created November 2, 2012 21:29
Show Gist options
  • Save kdungs/4004460 to your computer and use it in GitHub Desktop.
Save kdungs/4004460 to your computer and use it in GitHub Desktop.
A simple simulation of the Monty Hall Problem.
#!/usr/bin/env python
# coding=utf-8
from __future__ import division
import itertools as it
import random as r
from sys import argv
def play_round(switch_choice=True):
doors = [1, 2, 3]
player_pick = r.choice(doors)
master_pick = r.choice(doors)
reveal_pick = r.choice(filter(
lambda d: d != player_pick and d != master_pick,
doors
))
if switch_choice:
player_pick = filter(
lambda d: d != player_pick and d != reveal_pick,
doors
)[0]
return player_pick == master_pick
if __name__ == "__main__":
N_rounds = 1000000
if len(argv) > 1:
N_rounds = int(argv[1])
print("Playing {} rounds for each strategy.".format(N_rounds))
result_switch = len(filter(
lambda play: play(),
it.repeat(play_round, N_rounds))
)/N_rounds
result_stay = len(filter(
lambda play: play(switch_choice=False),
it.repeat(play_round, N_rounds))
)/N_rounds
print("Switch: {:.0%}".format(result_switch))
print("Stay : {:.0%}".format(result_stay))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment