The question is from Automate the Boring Stuff with Python and asks us to find the number of streaks of six heads or six tails that come up when a coin is tossed 100 times.
Coin Flip Streaks:
For this exercise, we’ll try doing an experiment. If you flip a coin 100 times and write down an “H” for each heads and “T” for each tails, you’ll create a list that looks like “T T T T H H H H T T.” If you ask a human to make up 100 random coin flips, you’ll probably end up with alternating head-tail results like “H T H T H H T H T T,” which looks random (to humans), but isn’t mathematically random. A human will almost never write down a streak of six heads or six tails in a row, even though it is highly likely to happen in truly random coin flips. Humans are predictably bad at being random.
Write a program to find out how often a streak of six heads or a streak of six tails comes up in a randomly generated list of heads and tails. Your program breaks up the experiment into two parts: the first part generates a list of randomly selected 'heads' and 'tails' values, and the second part checks if there is a streak in it. Put all of this code in a loop that repeats the experiment 10,000 times so we can find out what percentage of the coin flips contains a streak of six heads or tails in a row. As a hint, the function call random.randint(0, 1) will return a 0 value 50% of the time and a 1 value the other 50% of the time.
def streakFinder(inputList): import copy count=0 delList=copy.copy(inputList) # The list is copied to another reference so that it can be safely modified without affecting the original list try: # When the last element remains, there is no element left that can calculate the difference-->['H','H'] while len(delList)!=0: i=0 if delList[i]=='H': j=delList.index('T') else: j=delList.index('H') if j-i>=6: count+=1 del delList[i:j] except: # The error generated is dealt here. if len(delList)>=6: count+=1 return count
The inputList is the randomly generated list of H and T resulting from 100 coin tosses.
My solution gives me the correct answer. However, I would like to know if there is a better way to approach or solve this problem. If there are any errors, please point them out as I'm a beginner.