# monte_carlo_with_coins.py

# We know from math that if you flip a coin 4 times, the odds
# of getting at least 2 heads is 11/16, or 0.6875.
# Here, we will assume we don't know that, and we will use
# Monte Carlo methods to simulate coin flips and demonstrate this result.

import random

def flipCoin():
    return random.choice(['H', 'T'])

def flipCoins(times):
    result = [ ]
    for i in range(times):
        result.append(flipCoin())
    return result

def trialSucceeds():
    flips = flipCoins(4)
    return (flips.count('H') >= 2)

def oddsOfatLeastTwoHeadsInFourFlips(trials=100):
    successes = 0
    for trial in range(trials):
        if trialSucceeds() == True:
            successes += 1
    return successes / trials

trials = 10
answer = oddsOfatLeastTwoHeadsInFourFlips(trials)
realAnswer = 11/16 # from math

print('Estimating the odds of getting at least 2 heads in 4 coin flips')
print('Using', trials, 'trials (the more, the better)')
print('Computed answer (from Monte Carlo):', answer)
print('Actual answer (from math):', realAnswer)
print('Accuracy:',1 - abs(answer - realAnswer)/realAnswer)
if (trials < 10000):
    print('*** Increase the # of trials to get more accuracy! ***')
