Below is the wording from the problem in Automate the Boring Stuff book. The bold text leads me to believe that I should be checking for a streak and not multiple streaks within each experiment of 100 flips. With that assumption in mind, I would appreciate any feedback on my solution and comments to the problem posted below. I'm a beginner and have only included code that I have learned up to this point in the book.
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.
# importing the randint function from the random module
from random import randint
# creating variables for the number of streaks, current streak and coin flip results
numberOfStreaks = 0
streak = 0
results = []
# creating a loop that repeats the experiment 10,000 times
for experimentNumber in range(10000):
# first part of the experiment- 100 coin flips using randint
# for loop that specifies a range of 100 flips
for i in range(100):
# using the append method to add flip outcome to the results variable
results.append(randint(0, 1))
# second part of the experiment- checks flip results for a streak
# for loop where the range is equal to the length of the results variable
for i in range(len(results)):
# if statement for the first flip to start the streak
if i == 0:
# augmented assignment operator used for consistency
streak += 1
# else if statement to check for repeating values
# checks if the current indexed value is equal to the indexed value before it
elif results[i] == results[i - 1]:
# if the values are the same, the streak increases
streak += 1
# else statement for when it's not the first flip or a repeating value
else:
# resets the streak
streak = 1
# if statement for when the streak reaches 6
if streak == 6:
# registers a streak of six
numberOfStreaks += 1
# takes the string down to 0 after has hit 6
streak -= 6
# breaks the loop after a streak has come up
break
# resets the results list for the next expirementNumber
results = []
# find out what percentage contains a streak of six heads or six tails in a row
print('Chance of streak: %s%%' % (numberOfStreaks / 100))