import numpy as np
import pandas as pd
%matplotlib inline
import matplotlib.pyplot as plt
plt.style.use('fivethirtyeight')
outcomes = np.array(['heads', 'tails'])
np.random.choice(outcomes)
'heads'
np.random.choice(outcomes, 10)
array(['tails', 'tails', 'heads', 'heads', 'tails', 'heads', 'tails', 'tails', 'tails', 'heads'], dtype='<U5')
np.random.choice(outcomes, 10) == 'heads'
array([False, False, True, True, True, False, False, False, True, True])
sum(np.random.choice(outcomes, 10) == 'heads')
7
sum(np.random.choice(outcomes, 10) == 'tails')
5
flips = np.random.choice(outcomes, 10)
sum(flips == 'heads')
6
sum(flips == 'tails')
4
def heads_in_100_tosses():
return sum(np.random.choice(outcomes, 100) == 'heads')
results = np.array([])
for i in np.arange(10000):
results = np.append(results, heads_in_100_tosses())
results
array([59., 47., 41., ..., 49., 40., 48.])
heads = pd.DataFrame({'Heads': results })
heads.head()
Heads | |
---|---|
0 | 59.0 |
1 | 47.0 |
2 | 41.0 |
3 | 47.0 |
4 | 48.0 |
heads.hist('Heads', bins=np.arange(24.5, 76.5), ec='white');
doors = np.array(['car', 'first goat', 'second goat'])
doors
array(['car', 'first goat', 'second goat'], dtype='<U11')
goats = np.array(['first goat', 'second goat'])
def other_goat(a_goat):
if a_goat == 'first goat':
return 'second goat'
elif a_goat == 'second goat':
return 'first goat'
other_goat('first goat')
'second goat'
other_goat('wheeler hall')
def monty_hall():
contestant_choice = np.random.choice(doors)
if contestant_choice == 'first goat':
monty_choice = 'second goat'
remaining_door = 'car'
elif contestant_choice == 'second goat':
monty_choice = 'first goat'
remaining_door = 'car'
elif contestant_choice == 'car':
monty_choice = np.random.choice(goats)
remaining_door = other_goat(monty_choice)
return [contestant_choice, monty_choice, remaining_door]
monty_hall()
['second goat', 'first goat', 'car']
listy = []
for i in range(3000):
x = monty_hall()
listy.append(x)
listy = pd.DataFrame(listy, columns=(['Guess', 'Revealed', 'Remaining']))
games = listy
games
Guess | Revealed | Remaining | |
---|---|---|---|
0 | first goat | second goat | car |
1 | car | first goat | second goat |
2 | second goat | first goat | car |
3 | first goat | second goat | car |
4 | second goat | first goat | car |
... | ... | ... | ... |
2995 | car | second goat | first goat |
2996 | first goat | second goat | car |
2997 | first goat | second goat | car |
2998 | first goat | second goat | car |
2999 | car | first goat | second goat |
3000 rows × 3 columns
games.groupby(by='Remaining')[['Remaining']].count()
Remaining | |
---|---|
Remaining | |
car | 1986 |
first goat | 502 |
second goat | 512 |
games.groupby(by='Guess')[['Guess']].count()
Guess | |
---|---|
Guess | |
car | 1014 |
first goat | 982 |
second goat | 1004 |