Skip to content
Advertisement

Find the percentage of coin streaks

I’m trying to 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 of 100 flips and repeat this 10000 times to find percentage of the coin flips contains a streak of six heads or tails in a row.

My code is like this, and it’s some sort of working. **What I wonder is if it’s giving right results: **

import random
numberOfStreaks = 0
# Code that creates a list of 100 'heads' or 'tails' values.
for experimentNumber in range(10000):
    results = []
    for experiment in range(100):
        x = random.randint(1, 2)
        if x == 1:
            results.append('H')
        else:
            results.append('T')
    # Code that checks if there is a streak of 6 heads or tails in a row.
    currentStreak = 0
    previousResult = results[0]

    for result in results:
        if currentStreak == 6:
            numberOfStreaks += 1
            currentStreak = 0
        if result == previousResult:
            currentStreak += 1
            previousResult = result

print('Chance of streak: %s%%' % (numberOfStreaks / 100))

Advertisement

Answer

When you are getting a 7th repetition of heads or tails, it should be counted as a streak because the last 6 flips do form streak. By reseting the count after 6 you are underestimating the number of streaks.

From a probability standpoint, the result you are printing is not a measure of “chance” (that would never go above 100%) but is closer to a mathematical expectancy (i.e. sum of expected values multiplied by their respective probability). Your code produces a sampling of actual attempts but the calculations are not meaningful unless they can be compared to proper probability figures.

here’s how I would implement this sampling and express the results:

import random
from itertools import accumulate
expCount   = 10000
expSize    = 100
streakSize = 6

numberOfStreaks = 0
for experimentNumber in range(expCount):
    results = [random.choice("HT") for _ in range(expSize)]
    consec  = [int(a==b) for a,b in zip(results,results[1:])]
    streaks = sum( s+1>=streakSize for s in accumulate(consec,lambda s,m:s*m+m))
    numberOfStreaks += streaks

ratio = numberOfStreaks / expCount
print(f'Obtained {numberOfStreaks} streaks of {streakSize} head/tail on {expCount} runs of {expSize} flips. On average {ratio:.2f} streaks per run')
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement