CMU Coding Bootcamp
at main 29 lines 689 B view raw
1from random import choice 2 3def flipCoin() -> str: 4 return choice("HT") 5 6def estimateProbability(trials: int) -> float: 7 heads = 0 8 for _ in range(trials): 9 tosses: list[str] = [] 10 for _ in range(5): 11 tosses.append(flipCoin()) 12 if len([h for h in tosses if h == "H"]) == 2: 13 heads += 1 14 else: 15 return heads / trials 16 17 18def testTwoHeadsInFiveFlipsProblem(): 19 print('Testing the twoHeadsInFiveFlips Problem...', end='') 20 trials = 10**5 21 p = estimateProbability(trials) 22 print(p) 23 assert(0.30 <= p <= 0.32) # actual answer is about 0.313 24 print('Passed!') 25 26def main(): 27 testTwoHeadsInFiveFlipsProblem() 28 29main()