In [1]:
from datascience import *
%matplotlib inline

import matplotlib.pyplot as plt
plt.style.use('fivethirtyeight')
import numpy as np
import warnings
warnings.simplefilter(action='ignore', category=np.VisibleDeprecationWarning)

Simulation¶

In [2]:
coin = make_array('heads', 'tails')
In [3]:
np.random.choice(coin)
Out[3]:
'tails'
In [4]:
np.random.choice(coin, 10)
Out[4]:
array(['heads', 'heads', 'tails', 'heads', 'tails', 'tails', 'heads',
       'tails', 'tails', 'tails'],
      dtype='<U5')
In [5]:
sum(np.random.choice(coin, 10) == 'heads')
Out[5]:
6
In [6]:
# Simulate one outcome

def heads_in_100_tosses():
    return sum(np.random.choice(coin, 100) == 'heads')
In [7]:
# Decide how many times you want to repeat the experiment

num_simulations = 10000
In [8]:
# Simulate that many outcomes

outcomes = make_array()

for i in np.arange(num_simulations):
    outcomes = np.append(outcomes, heads_in_100_tosses())
    
outcomes
Out[8]:
array([ 46.,  39.,  56., ...,  51.,  42.,  44.])
In [9]:
heads = Table().with_column('Heads', outcomes)
heads.hist(bins = np.arange(24.5, 76.5))

Chance¶

Probability Question¶

In [ ]:
 
In [ ]:
 
In [ ]:
 

Another Question¶

In [ ]:
 
In [ ]:
 
In [ ]:
 

Complement Rule¶

In [ ]:
 
In [ ]:
 
In [ ]:
 

The Monty Hall Problem¶

In [10]:
doors = make_array('car', 'first goat', 'second goat')
doors
Out[10]:
array(['car', 'first goat', 'second goat'],
      dtype='<U11')
In [11]:
def other_goat(x):
    if x == 'first goat':
        return 'second goat'
    elif x == 'second goat':
        return 'first goat'
In [12]:
goats = [other_goat('first goat'), other_goat('second goat')]
In [13]:
def monty_hall():
    """Return 
    [contestant's guess, what Monty reveals, what remains behind the other door]"""
    
    contestant_choice = np.random.choice(doors)
    
    if contestant_choice == 'first goat':
        monty_choice = 'second goat'
        remaining_choice = 'car'
    
    if contestant_choice == 'second goat':
        monty_choice = 'first goat'
        remaining_choice = 'car'
    
    if contestant_choice == 'car':
        monty_choice = np.random.choice(goats)
        remaining_choice = other_goat(monty_choice)
        
    return [contestant_choice, monty_choice, remaining_choice]
In [14]:
monty_hall()
Out[14]:
['car', 'first goat', 'second goat']
In [15]:
results = Table(['Guess', 'Revealed', 'Remaining'])

for i in np.arange(10000):
    results.append(monty_hall())
In [16]:
results.show(3)
Guess Revealed Remaining
second goat first goat car
second goat first goat car
car first goat second goat

... (9997 rows omitted)

In [17]:
results.group('Remaining').barh('Remaining')
In [18]:
results.group('Guess').barh('Guess')