I am attempting to complete the coin flip streaks problem from automate the boring stuff with python. My code works fine but my only concern is the phrasing of the task.
Does the question want us to find the number of samples (100 flips) that contain at least one streak and divide that by the total number of samples (10,000)
Or are we supposed to find the total number of streaks (6H or 6T) in all samples and divide that by 10,000?
My solution was for the first option but I make no distinction between one streak and several.
My code and the question are listed below.
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.
import random
import re
totalRuns = 0
streakScore = 0
def coinFips():
global streakScore,totalRuns
# Return results into a single string for regular expressions
results = ''
for i in range(100):
value = random.randint(0, 1)
if value == 0:
results += "H"
elif value == 1:
results += "T"
# Use regular expressions to check results sting
match = re.findall(r'(HHHHHH|TTTTTT)', results)
if len(match) > 0:
streakScore = streakScore + 1
totalRuns = totalRuns + 1
for i in range(10000):
coinFips()
print("The Chance of a streak is: {}%".format(round(streakScore/totalRuns * 100)))