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)
coin = make_array('heads', 'tails')
np.random.choice(coin)
'tails'
np.random.choice(coin, 10)
array(['heads', 'heads', 'tails', 'heads', 'tails', 'tails', 'heads', 'tails', 'tails', 'tails'], dtype='<U5')
sum(np.random.choice(coin, 10) == 'heads')
6
# Simulate one outcome
def heads_in_100_tosses():
return sum(np.random.choice(coin, 100) == 'heads')
# Decide how many times you want to repeat the experiment
num_simulations = 10000
# Simulate that many outcomes
outcomes = make_array()
for i in np.arange(num_simulations):
outcomes = np.append(outcomes, heads_in_100_tosses())
outcomes
array([ 46., 39., 56., ..., 51., 42., 44.])
heads = Table().with_column('Heads', outcomes)
heads.hist(bins = np.arange(24.5, 76.5))
doors = make_array('car', 'first goat', 'second goat')
doors
array(['car', 'first goat', 'second goat'], dtype='<U11')
def other_goat(x):
if x == 'first goat':
return 'second goat'
elif x == 'second goat':
return 'first goat'
goats = [other_goat('first goat'), other_goat('second goat')]
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]
monty_hall()
['car', 'first goat', 'second goat']
results = Table(['Guess', 'Revealed', 'Remaining'])
for i in np.arange(10000):
results.append(monty_hall())
results.show(3)
Guess | Revealed | Remaining |
---|---|---|
second goat | first goat | car |
second goat | first goat | car |
car | first goat | second goat |
... (9997 rows omitted)
results.group('Remaining').barh('Remaining')
results.group('Guess').barh('Guess')