Homework 0

Due Tuesday, September 10 (but no submission is required)


Welcome to CS109 / STAT121 / AC209 / E-109 (http://cs109.org/). In this class, we will be using a variety of tools that will require some initial configuration. To ensure everything goes smoothly moving forward, we will setup the majority of those tools in this homework. While some of this will likely be dull, doing it now will enable us to do more exciting work in the weeks that follow without getting bogged down in further software configuration. This homework will not be graded, however it is essential that you complete it timely since it will enable us to set up your accounts. You do not have to hand anything in, with the exception of filling out the online survey.

Class Survey, Piazza, and Introduction

Class Survey

Please complete the mandatory course survey located here. It should only take a few moments of your time. Once you fill in the survey we will sign you up to the course forum on Piazza and the dropbox system that you will use to hand in the homework. It is imperative that you fill out the survey on time as we use the provided information to sign you up for these services.

Piazza

Go to Piazza and sign up for the class using your Harvard e-mail address.

You will use Piazza as a forum for discussion, to find team members, to arrange appointments, and to ask questions. Piazza should be your primary form of communication with the staff. Use the staff e-mail (staff@cs109.org) only for individual requests, e.g., to excuse yourself from a mandatory guest lecture. All readings, homeworks, and project descriptions will be announced on Piazza first.

Introduction

Once you are signed up to the Piazza course forum, introduce yourself to your classmates and course staff with a follow-up post in the introduction thread. Include your name/nickname, your affiliation, why you are taking this course, and tell us something interesting about yourself (e.g., an industry job, an unusual hobby, past travels, or a cool project you did, etc.). Also tell us whether you have experience with data science.

Programming expectations

All the assignments and labs for this class will use Python and, for the most part, the browser-based IPython notebook format you are currently viewing. Knowledge of Python is not a prerequisite for this course, provided you are comfortable learning on your own as needed. While we have strived to make the programming component of this course straightforward, we will not devote much time to teaching prorgramming or Python syntax. Basically, you should feel comfortable with:

  • How to look up Python syntax on Google and StackOverflow.
  • Basic programming concepts like functions, loops, arrays, dictionaries, strings, and if statements.
  • How to learn new libraries by reading documentation.
  • Asking questions on StackOverflow or Piazza.

There are many online tutorials to introduce you to scientific python programming. Here is one that is very nice. Lectures 1-4 are most relevant to this class.

Getting Python

You will be using Python throughout the course, including many popular 3rd party Python libraries for scientific computing. Anaconda is an easy-to-install bundle of Python and most of these libraries. We recommend that you use Anaconda for this course.

Please visit this page and follow the instructions to set up Python

Hello, Python

The IPython notebook is an application to build interactive computational notebooks. You'll be using them to complete labs and homework. Once you've set up Python, please download this page, and open it with IPython by typing

ipython notebook <name_of_downloaded_file>

For the rest of the assignment, use your local copy of this page, running on IPython.

Notebooks are composed of many "cells", which can contain text (like this one), or code (like the one below). Double click on the cell below, and evaluate it by clicking the "play" button above, for by hitting shift + enter

Note: This HW was completed in Python 3. Run time errors are expected upon running with Python 2.x.


In [ ]:
x = [10, 20, 30, 40, 50]
for item in x:
    print "Item is ", item

Python Libraries

We will be using a several different libraries throughout this course. If you've successfully completed the installation instructions, all of the following statements should run.


In [1]:
#IPython is what you are using now to run the notebook
import IPython
print ("IPython version:      %6.6s (need at least 1.0)" % IPython.__version__)

# Numpy is a library for working with Arrays
import numpy as np
print ("Numpy version:        %6.6s (need at least 1.7.1)" % np.__version__)

# SciPy implements many different numerical algorithms
import scipy as sp
print ("SciPy version:        %6.6s (need at least 0.12.0)" % sp.__version__)

# Pandas makes working with data tables easier
import pandas as pd
print ("Pandas version:       %6.6s (need at least 0.11.0)" % pd.__version__)

# Module for plotting
import matplotlib
print ("Mapltolib version:    %6.6s (need at least 1.2.1)" % matplotlib.__version__)

# SciKit Learn implements several Machine Learning algorithms
import sklearn
print ("Scikit-Learn version: %6.6s (need at least 0.13.1)" % sklearn.__version__)

# Requests is a library for getting data from the Web
import requests
print ("requests version:     %6.6s (need at least 1.2.3)" % requests.__version__)

# Networkx is a library for working with networks
import networkx as nx
print ("NetworkX version:     %6.6s (need at least 1.7)" % nx.__version__)

#BeautifulSoup is a library to parse HTML and XML documents
#import beautifulsoup4
import bs4
print ("BeautifulSoup version:%6.6s (need at least 3.2)" % bs4.__version__)

#MrJob is a library to run map reduce jobs on Amazon's computers
import mrjob
print ("Mr Job version:       %6.6s (need at least 0.4)" % mrjob.__version__)

#Pattern has lots of tools for working with data from the internet
import pattern
print ("Pattern version:      %6.6s (need at least 2.6)" % pattern.__version__)


IPython version:       4.2.0 (need at least 1.0)
Numpy version:        1.11.0 (need at least 1.7.1)
SciPy version:        0.17.1 (need at least 0.12.0)
Pandas version:       0.18.1 (need at least 0.11.0)
Mapltolib version:     1.5.1 (need at least 1.2.1)
Scikit-Learn version: 0.17.1 (need at least 0.13.1)
requests version:     2.10.0 (need at least 1.2.3)
NetworkX version:       1.11 (need at least 1.7)
BeautifulSoup version: 4.4.1 (need at least 3.2)
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-1-de0e30198d34> in <module>()
     37 
     38 #MrJob is a library to run map reduce jobs on Amazon's computers
---> 39 import mrjob
     40 print ("Mr Job version:       %6.6s (need at least 0.4)" % mrjob.__version__)
     41 

ImportError: No module named mrjob

If any of these libraries are missing or out of date, you will need to install them and restart IPython

Hello matplotlib

The notebook integrates nicely with Matplotlib, the primary plotting package for python. This should embed a figure of a sine wave:


In [5]:
#this line prepares IPython for working with matplotlib
%matplotlib inline  

# this actually imports matplotlib
import matplotlib.pyplot as plt  

x = np.linspace(0, 10, 30)  #array of 30 points from 0 to 10
y = np.sin(x)
z = y + np.random.normal(size=30) * .2
plt.plot(x, y, 'ro-', label='A sine wave')
plt.plot(x, z, 'b-', label='Noisy sine')
plt.legend(loc = 'lower right')
plt.xlabel("X axis")
plt.ylabel("Y axis")


Out[5]:
<matplotlib.text.Text at 0x117b8bc88>

If that last cell complained about the %matplotlib line, you need to update IPython to v1.0, and restart the notebook. See the installation page

Hello Numpy

The Numpy array processing library is the basis of nearly all numerical computing in Python. Here's a 30 second crash course. For more details, consult Chapter 4 of Python for Data Analysis, or the Numpy User's Guide


In [27]:
print ("Make a 3 row x 4 column array of random numbers")
x = np.random.random((3, 4))
print (x)
print

print ("Add 1 to every element")
x = x + 1
print (x)
print

print ("Get the element at row 1, column 2")
print (x[1, 2])
print

# The colon syntax is called "slicing" the array. 
print ("Get the first row")
print (x[0, :])
print

print ("Get every 2nd column of the first row")
print (x[0, ::2])
print


Make a 3 row x 4 column array of random numbers
[[ 0.22855629  0.17427162  0.64526004  0.74295902]
 [ 0.34273758  0.70386141  0.35124342  0.73847942]
 [ 0.60740051  0.63028822  0.60735982  0.1842157 ]]
Add 1 to every element
[[ 1.22855629  1.17427162  1.64526004  1.74295902]
 [ 1.34273758  1.70386141  1.35124342  1.73847942]
 [ 1.60740051  1.63028822  1.60735982  1.1842157 ]]
Get the element at row 1, column 2
1.35124342377
Get the first row
[ 1.22855629  1.17427162  1.64526004  1.74295902]
Get every 2nd column of the first row
[ 1.22855629  1.64526004]
Out[27]:
<function print>

In [ ]:
x = np.random

Print the maximum, minimum, and mean of the array. This does not require writing a loop. In the code cell below, type x.m<TAB>, to find built-in operations for common array statistics like this


In [12]:
#your code here
print (x.max())
print (x.min())
print (x.mean())


1.92291326396
1.00098833104
1.45798265717

Call the x.max function again, but use the axis keyword to print the maximum of each row in x.


In [15]:
#your code here
x.max(axis = 1)


Out[15]:
array([ 1.92291326,  1.43728661,  1.81705175])

Here's a way to quickly simulate 500 coin "fair" coin tosses (where the probabily of getting Heads is 50%, or 0.5)


In [18]:
x = np.random.binomial(500, .5)
x = np.random.binomial?
print ("number of heads:", x)


number of heads: 213

In [19]:
x = np.random.binomial

Repeat this simulation 500 times, and use the plt.hist() function to plot a histogram of the number of Heads (1s) in each simulation


In [26]:
#your code here
heads = []
for i in range(1,500):
    heads.append(np.random.binomial(500, .5))
plt.hist(heads, bins =500)


Out[26]:
(array([  2.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   1.,   0.,   0.,
          0.,   0.,   0.,   0.,   0.,   3.,   0.,   0.,   0.,   0.,   0.,
          0.,   0.,   0.,   1.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,
          0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   1.,   0.,   0.,
          0.,   0.,   0.,   0.,   0.,   0.,   2.,   0.,   0.,   0.,   0.,
          0.,   0.,   0.,   2.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,
          2.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   3.,   0.,
          0.,   0.,   0.,   0.,   0.,   0.,   3.,   0.,   0.,   0.,   0.,
          0.,   0.,   0.,   6.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,
          0.,   3.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   5.,   0.,
          0.,   0.,   0.,   0.,   0.,   0.,  10.,   0.,   0.,   0.,   0.,
          0.,   0.,   0.,   0.,  11.,   0.,   0.,   0.,   0.,   0.,   0.,
          0.,  12.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,  15.,   0.,
          0.,   0.,   0.,   0.,   0.,   0.,   0.,  13.,   0.,   0.,   0.,
          0.,   0.,   0.,   0.,  10.,   0.,   0.,   0.,   0.,   0.,   0.,
          0.,   5.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,  11.,
          0.,   0.,   0.,   0.,   0.,   0.,   0.,  18.,   0.,   0.,   0.,
          0.,   0.,   0.,   0.,  19.,   0.,   0.,   0.,   0.,   0.,   0.,
          0.,   0.,  19.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,  15.,
          0.,   0.,   0.,   0.,   0.,   0.,   0.,  15.,   0.,   0.,   0.,
          0.,   0.,   0.,   0.,   0.,  20.,   0.,   0.,   0.,   0.,   0.,
          0.,   0.,  15.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,  16.,
          0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,  16.,   0.,   0.,
          0.,   0.,   0.,   0.,   0.,  15.,   0.,   0.,   0.,   0.,   0.,
          0.,   0.,  13.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,
         13.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,  17.,   0.,   0.,
          0.,   0.,   0.,   0.,   0.,  23.,   0.,   0.,   0.,   0.,   0.,
          0.,   0.,   0.,  17.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,
         18.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,  12.,   0.,   0.,
          0.,   0.,   0.,   0.,   0.,   0.,  14.,   0.,   0.,   0.,   0.,
          0.,   0.,   0.,   9.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,
          7.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   8.,   0.,
          0.,   0.,   0.,   0.,   0.,   0.,  10.,   0.,   0.,   0.,   0.,
          0.,   0.,   0.,   7.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,
          0.,   7.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   4.,   0.,
          0.,   0.,   0.,   0.,   0.,   0.,   5.,   0.,   0.,   0.,   0.,
          0.,   0.,   0.,   0.,   4.,   0.,   0.,   0.,   0.,   0.,   0.,
          0.,   1.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   6.,   0.,
          0.,   0.,   0.,   0.,   0.,   0.,   0.,   4.,   0.,   0.,   0.,
          0.,   0.,   0.,   0.,   3.,   0.,   0.,   0.,   0.,   0.,   0.,
          0.,   3.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,
          0.,   0.,   0.,   0.,   0.,   0.,   0.,   3.,   0.,   0.,   0.,
          0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,
          0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,
          0.,   0.,   0.,   0.,   0.,   0.,   0.,   1.,   0.,   0.,   0.,
          0.,   0.,   0.,   0.,   1.]),
 array([ 221.  ,  221.12,  221.24,  221.36,  221.48,  221.6 ,  221.72,
         221.84,  221.96,  222.08,  222.2 ,  222.32,  222.44,  222.56,
         222.68,  222.8 ,  222.92,  223.04,  223.16,  223.28,  223.4 ,
         223.52,  223.64,  223.76,  223.88,  224.  ,  224.12,  224.24,
         224.36,  224.48,  224.6 ,  224.72,  224.84,  224.96,  225.08,
         225.2 ,  225.32,  225.44,  225.56,  225.68,  225.8 ,  225.92,
         226.04,  226.16,  226.28,  226.4 ,  226.52,  226.64,  226.76,
         226.88,  227.  ,  227.12,  227.24,  227.36,  227.48,  227.6 ,
         227.72,  227.84,  227.96,  228.08,  228.2 ,  228.32,  228.44,
         228.56,  228.68,  228.8 ,  228.92,  229.04,  229.16,  229.28,
         229.4 ,  229.52,  229.64,  229.76,  229.88,  230.  ,  230.12,
         230.24,  230.36,  230.48,  230.6 ,  230.72,  230.84,  230.96,
         231.08,  231.2 ,  231.32,  231.44,  231.56,  231.68,  231.8 ,
         231.92,  232.04,  232.16,  232.28,  232.4 ,  232.52,  232.64,
         232.76,  232.88,  233.  ,  233.12,  233.24,  233.36,  233.48,
         233.6 ,  233.72,  233.84,  233.96,  234.08,  234.2 ,  234.32,
         234.44,  234.56,  234.68,  234.8 ,  234.92,  235.04,  235.16,
         235.28,  235.4 ,  235.52,  235.64,  235.76,  235.88,  236.  ,
         236.12,  236.24,  236.36,  236.48,  236.6 ,  236.72,  236.84,
         236.96,  237.08,  237.2 ,  237.32,  237.44,  237.56,  237.68,
         237.8 ,  237.92,  238.04,  238.16,  238.28,  238.4 ,  238.52,
         238.64,  238.76,  238.88,  239.  ,  239.12,  239.24,  239.36,
         239.48,  239.6 ,  239.72,  239.84,  239.96,  240.08,  240.2 ,
         240.32,  240.44,  240.56,  240.68,  240.8 ,  240.92,  241.04,
         241.16,  241.28,  241.4 ,  241.52,  241.64,  241.76,  241.88,
         242.  ,  242.12,  242.24,  242.36,  242.48,  242.6 ,  242.72,
         242.84,  242.96,  243.08,  243.2 ,  243.32,  243.44,  243.56,
         243.68,  243.8 ,  243.92,  244.04,  244.16,  244.28,  244.4 ,
         244.52,  244.64,  244.76,  244.88,  245.  ,  245.12,  245.24,
         245.36,  245.48,  245.6 ,  245.72,  245.84,  245.96,  246.08,
         246.2 ,  246.32,  246.44,  246.56,  246.68,  246.8 ,  246.92,
         247.04,  247.16,  247.28,  247.4 ,  247.52,  247.64,  247.76,
         247.88,  248.  ,  248.12,  248.24,  248.36,  248.48,  248.6 ,
         248.72,  248.84,  248.96,  249.08,  249.2 ,  249.32,  249.44,
         249.56,  249.68,  249.8 ,  249.92,  250.04,  250.16,  250.28,
         250.4 ,  250.52,  250.64,  250.76,  250.88,  251.  ,  251.12,
         251.24,  251.36,  251.48,  251.6 ,  251.72,  251.84,  251.96,
         252.08,  252.2 ,  252.32,  252.44,  252.56,  252.68,  252.8 ,
         252.92,  253.04,  253.16,  253.28,  253.4 ,  253.52,  253.64,
         253.76,  253.88,  254.  ,  254.12,  254.24,  254.36,  254.48,
         254.6 ,  254.72,  254.84,  254.96,  255.08,  255.2 ,  255.32,
         255.44,  255.56,  255.68,  255.8 ,  255.92,  256.04,  256.16,
         256.28,  256.4 ,  256.52,  256.64,  256.76,  256.88,  257.  ,
         257.12,  257.24,  257.36,  257.48,  257.6 ,  257.72,  257.84,
         257.96,  258.08,  258.2 ,  258.32,  258.44,  258.56,  258.68,
         258.8 ,  258.92,  259.04,  259.16,  259.28,  259.4 ,  259.52,
         259.64,  259.76,  259.88,  260.  ,  260.12,  260.24,  260.36,
         260.48,  260.6 ,  260.72,  260.84,  260.96,  261.08,  261.2 ,
         261.32,  261.44,  261.56,  261.68,  261.8 ,  261.92,  262.04,
         262.16,  262.28,  262.4 ,  262.52,  262.64,  262.76,  262.88,
         263.  ,  263.12,  263.24,  263.36,  263.48,  263.6 ,  263.72,
         263.84,  263.96,  264.08,  264.2 ,  264.32,  264.44,  264.56,
         264.68,  264.8 ,  264.92,  265.04,  265.16,  265.28,  265.4 ,
         265.52,  265.64,  265.76,  265.88,  266.  ,  266.12,  266.24,
         266.36,  266.48,  266.6 ,  266.72,  266.84,  266.96,  267.08,
         267.2 ,  267.32,  267.44,  267.56,  267.68,  267.8 ,  267.92,
         268.04,  268.16,  268.28,  268.4 ,  268.52,  268.64,  268.76,
         268.88,  269.  ,  269.12,  269.24,  269.36,  269.48,  269.6 ,
         269.72,  269.84,  269.96,  270.08,  270.2 ,  270.32,  270.44,
         270.56,  270.68,  270.8 ,  270.92,  271.04,  271.16,  271.28,
         271.4 ,  271.52,  271.64,  271.76,  271.88,  272.  ,  272.12,
         272.24,  272.36,  272.48,  272.6 ,  272.72,  272.84,  272.96,
         273.08,  273.2 ,  273.32,  273.44,  273.56,  273.68,  273.8 ,
         273.92,  274.04,  274.16,  274.28,  274.4 ,  274.52,  274.64,
         274.76,  274.88,  275.  ,  275.12,  275.24,  275.36,  275.48,
         275.6 ,  275.72,  275.84,  275.96,  276.08,  276.2 ,  276.32,
         276.44,  276.56,  276.68,  276.8 ,  276.92,  277.04,  277.16,
         277.28,  277.4 ,  277.52,  277.64,  277.76,  277.88,  278.  ,
         278.12,  278.24,  278.36,  278.48,  278.6 ,  278.72,  278.84,
         278.96,  279.08,  279.2 ,  279.32,  279.44,  279.56,  279.68,
         279.8 ,  279.92,  280.04,  280.16,  280.28,  280.4 ,  280.52,
         280.64,  280.76,  280.88,  281.  ]),
 <a list of 500 Patch objects>)

The Monty Hall Problem

Here's a fun and perhaps surprising statistical riddle, and a good way to get some practice writing python functions

In a gameshow, contestants try to guess which of 3 closed doors contain a cash prize (goats are behind the other two doors). Of course, the odds of choosing the correct door are 1 in 3. As a twist, the host of the show occasionally opens a door after a contestant makes his or her choice. This door is always one of the two the contestant did not pick, and is also always one of the goat doors (note that it is always possible to do this, since there are two goat doors). At this point, the contestant has the option of keeping his or her original choice, or swtiching to the other unopened door. The question is: is there any benefit to switching doors? The answer surprises many people who haven't heard the question before.

We can answer the problem by running simulations in Python. We'll do it in several parts.

First, write a function called simulate_prizedoor. This function will simulate the location of the prize in many games -- see the detailed specification below:


In [37]:
"""
Function
--------
simulate_prizedoor

Generate a random array of 0s, 1s, and 2s, representing
hiding a prize between door 0, door 1, and door 2

Parameters
----------
nsim : int
    The number of simulations to run

Returns
-------
sims : array
    Random array of 0s, 1s, and 2s

Example
-------
>>> print simulate_prizedoor(3)
array([0, 0, 2])
"""
def simulate_prizedoor(nsim):
    #compute here
    answer =np.random.random_integers(0,2,nsim)
    return answer
#your code here
print (simulate_prizedoor(10))


[1 1 1 0 1 2 1 1 2 1]

Next, write a function that simulates the contestant's guesses for nsim simulations. Call this function simulate_guess. The specs:


In [38]:
"""
Function
--------
simulate_guess

Return any strategy for guessing which door a prize is behind. This
could be a random strategy, one that always guesses 2, whatever.

Parameters
----------
nsim : int
    The number of simulations to generate guesses for

Returns
-------
guesses : array
    An array of guesses. Each guess is a 0, 1, or 2

Example
-------
>>> print simulate_guess(5)
array([0, 0, 0, 0, 0])
"""
#your code here
def simulate_guess(nsim):
    #compute here
    answer =np.random.random_integers(0,1,nsim)
    return answer
#your code here
print (simulate_guess(10))


[0 0 0 1 1 1 1 0 0 0]

Next, write a function, goat_door, to simulate randomly revealing one of the goat doors that a contestant didn't pick.


In [48]:
"""
Function
--------
goat_door

Simulate the opening of a "goat door" that doesn't contain the prize,
and is different from the contestants guess

Parameters
----------
prizedoors : array
    The door that the prize is behind in each simulation
guesses : array
    THe door that the contestant guessed in each simulation

Returns
-------
goats : array
    The goat door that is opened for each simulation. Each item is 0, 1, or 2, and is different
    from both prizedoors and guesses

Examples
--------
>>> print goat_door(np.array([0, 1, 2]), np.array([1, 1, 1]))
>>> array([2, 2, 0])
"""
def goat_door(prizedoors, guesses):
    
    #strategy: generate random answers, and
    #keep updating until they satisfy the rule
    #that they aren't a prizedoor or a guess
    result = np.random.randint(0, 3, prizedoors.size)

    while True:
        bad = (result == prizedoors) | (result == guesses)
        if not bad.any():
            return result
        result[bad] = np.random.randint(0, 3, bad.sum())
   
print (goat_door(np.array([0, 1, 2,1]), np.array([1, 1, 1,1])))


[2 0 0 2]

Write a function, switch_guess, that represents the strategy of always switching a guess after the goat door is opened.


In [49]:
"""
Function
--------
switch_guess

The strategy that always switches a guess after the goat door is opened

Parameters
----------
guesses : array
     Array of original guesses, for each simulation
goatdoors : array
     Array of revealed goat doors for each simulation

Returns
-------
The new door after switching. Should be different from both guesses and goatdoors

Examples
--------
>>> print switch_guess(np.array([0, 1, 2]), np.array([1, 2, 1]))
>>> array([2, 0, 0])
"""
#your code here
def switch_guess(guesses, goatdoors):
    
    #strategy: generate random answers, and
    #keep updating until they satisfy the rule
    #that they aren't a guess or a goatdoor
    result = np.random.randint(0, 3, guesses.size)

    while True:
        bad = (result == guesses) | (result == goatdoors)
        if not bad.any():
            return result
        result[bad] = np.random.randint(0, 3, bad.sum())
print (switch_guess(np.array([0, 1, 2]), np.array([1, 2, 1])))


[2 0 0]

Last function: write a win_percentage function that takes an array of guesses and prizedoors, and returns the percent of correct guesses


In [56]:
"""
Function
--------
win_percentage

Calculate the percent of times that a simulation of guesses is correct

Parameters
-----------
guesses : array
    Guesses for each simulation
prizedoors : array
    Location of prize for each simulation

Returns
--------
percentage : number between 0 and 100
    The win percentage

Examples
---------
>>> print win_percentage(np.array([0, 1, 2]), np.array([0, 0, 0]))
33.333
"""
#your code here
def win_percentage(guesses, prizedoors):
    correct_guesses = guesses == prizedoors
    answer =  correct_guesses.sum()/guesses.size*100
    return answer
print (win_percentage(np.array([0, 1, 2]), np.array([0, 2, 2])))


66.6666666667

Now, put it together. Simulate 10000 games where contestant keeps his original guess, and 10000 games where the contestant switches his door after a goat door is revealed. Compute the percentage of time the contestant wins under either strategy. Is one strategy better than the other?


In [58]:
#your code here

#simulate prizedoors, guesses, goatdoors
prizedoors = simulate_prizedoor(10000)
guesses = simulate_guess(10000)
goatdoors = goat_door(prizedoors, guesses)
#compute win percent if keep original
print("Win Percentage - keep original")
print(win_percentage(guesses,prizedoors))
#compute win percent if switch guess
switchedguesses = switch_guess(guesses,goatdoors)
print("Win Percentage - switch guess")
print(win_percentage(switchedguesses,prizedoors))


Win Percentage - keep original
33.17
Win Percentage - switch guess
66.83

Many people find this answer counter-intuitive (famously, PhD mathematicians have incorrectly claimed the result must be wrong. Clearly, none of them knew Python).

One of the best ways to build intuition about why opening a Goat door affects the odds is to re-run the experiment with 100 doors and one prize. If the game show host opens 98 goat doors after you make your initial selection, would you want to keep your first pick or switch? Can you generalize your simulation code to handle the case of n doors?