17 Getting exactly two heads (combinatorics)#

%%html
<iframe width="700" height="400" src="https://www.youtube.com/embed/8TIben0bJpU/" frameborder="0" allowfullscreen></iframe>
import itertools
import numpy as np
import pandas as pd
from pandas import Series, DataFrame
import matplotlib.pyplot as plt
import seaborn as sns
from scipy import stats, special

khanacademy

Getting exactly two heads (combinatorics) fig 1Getting exactly two heads (combinatorics) fig 2

def P(cond, total_lst):
    cond_lst = list(filter(cond, total_lst))
    return len(cond_lst) / len(total_lst), cond_lst

def factorial(n):
    if n == 1:
        return 1
    else: 
        return n * factorial(n - 1)
    
def permutation_without_repetation(n, r):
    if n != r:
        return factorial(n) / factorial(n-r)
    else: # zero factorial
        return factorial(n) / factorial(1)
    
def combination_without_repetation(n, r):
    return permutation_without_repetation(n, r) * (1 / factorial(r))
p = ["".join(i) for i in itertools.product(['H', 'T'], repeat=4)]
p
['HHHH',
 'HHHT',
 'HHTH',
 'HHTT',
 'HTHH',
 'HTHT',
 'HTTH',
 'HTTT',
 'THHH',
 'THHT',
 'THTH',
 'THTT',
 'TTHH',
 'TTHT',
 'TTTH',
 'TTTT']
P(lambda x: x.replace('T', '') == 'H', p)
(0.25, ['HTTT', 'THTT', 'TTHT', 'TTTH'])
P(lambda x: x.replace('T', '') == 'HH', p)
(0.375, ['HHTT', 'HTHT', 'HTTH', 'THHT', 'THTH', 'TTHH'])
special.comb(4, 2) / len(p)
0.375