I'm a beginner, new both to coding and to Python and I'm using the book "Automate the boring stuff with Python" to learn; one of the practice projects of the first chapters is the following:
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.
My programm returns exactly double as much percentage as it should. (Expected: 79-80%, returned 159%). I've tried to fix my code by comparing it with the other replies I've found but, since I've used a different approach, I still don't understand why this happens, as everything looks right.
import random
Total = [] # Defines the list in which there will be all of the throws
Throw = ("H", "T") # Cases
for x in range(10000): # Repeats the 100 throws 10 000 times
for i in range(100):
Total.append(random.choice(Throw)) # Adds a random throw to the list "Total";
Join = " ".join(Total) # Creates a string to easily count the groups of T and H
N_T = Join.count("T T T T T T") # Counts the Numbers of groups of six Tails
N_H = Join.count("H H H H H H") # Counts the Numbers of groups of six Heads
print('Chance of streak: %s%%' % ((N_H N_T) / 100)) # Probability
I hope this wasn't a dumb question... Thank you for your help.
CodePudding user response:
You need to set borders for your search terms, like this:
N_T = Join.count("H T T T T T T H") # Counts the Numbers of groups of six Tails
N_H = Join.count("T H H H H H H T") # Counts the Numbers of groups of six Heads
because otherwise what would happen if you have the following sequence:
"T T T T T T T T T T T T"
It can find your pattern multiple times in that bigger sequence, which leads to more hits than 100%, which of course is plausible in that case.