Setup

Setup imports and the play function. Playing has the user start with Door 0. Then the winning door is also chosen at random. The user randomly switches also.


In [1]:
import random
import numpy as np
import matplotlib.pyplot as plt
import pandas

def play():
    choices = [0,1,2]
    userchooses = 0
    winning = random.choice(choices)
    hallchoices = [0,1,2]
    hallchoices.remove(userchooses)
    hallchooses = [i for i in hallchoices if i != winning][0]
    
    switch = (random.choice([0, 1]) == 1)
    if switch:
        userchooses = [i for i in [0,1,2] if i not in [userchooses, hallchooses]][0]
    return (userchooses == winning, switch, userchooses, hallchooses, winning)

Here's one example play.


In [2]:
outcome = play()
print("Did user win? %s" % outcome[0])
print("Did user switch? %s" % outcome[1])
print("What did user choose? %s" % outcome[2])
print("What did Hall choose? %s" % outcome[3])
print("What was the winning door? %s" % outcome[4])


Did user win? False
Did user switch? False
What did user choose? 0
What did Hall choose? 2
What was the winning door? 1

Play

A bunch of plays stored in a numpy array


In [3]:
trials = np.ndarray((100000, 5), dtype=np.int64)
for i in xrange(len(trials)):
    trials[i] = play()
trials[0]


Out[3]:
array([0, 1, 2, 1, 0])

In [4]:
np.sum(trials, 0)


Out[4]:
array([ 49846,  49937,  83163, 133515,  99807])

Use a DataFrame for a lot of convenience :-D


In [5]:
df = pandas.DataFrame(trials, columns=('wins', 'switch', 'userchooses', 'hallchooses', 'correctchoice'))

In [6]:
switch_outcomes = df[df['switch'] == 1]
print("Number of times when user switched: %d" % len(switch_outcomes))
print("Number of times the user won after switch: %d (%0.2f)" % (switch_outcomes['wins'].sum(), 100.0*switch_outcomes['wins'].sum()/len(switch_outcomes)))


Number of times when user switched: 49937
Number of times the user won after switch: 33222 (66.53)

Plots

Are we switching randomly?


In [11]:
ignore = plt.hist(df['switch'])


What does Hall choose? User always starts with Door 0. So, Hall never chooses 0 or a winner.


In [14]:
ignore = plt.hist(df['hallchooses'])


View of wins regardless of switching. Most things in play() are random. How does this look?


In [12]:
ignore = plt.hist(df['wins'])
ignore = plt.xticks((0,1), ("Lose", "Win"))


How does the user do if he/she switches?


In [9]:
ignore = plt.hist(df[df['switch'] == 1]['wins'])
ignore = plt.xticks((0,1), ("Lose", "Win"))


How does the user do if he/she doesn't switch?


In [10]:
ignore = plt.hist(df[df['switch'] == 0]['wins'])
ignore = plt.xticks((0,1), ("Lose", "Win"))