-2

I know there are lots of questions about the same problem, but I think I tried a bit of a different approach.

The objective is to write python code to:

(1) Simulate 10.000 samples of 100 flips each and record the Heads(H) and Tails(T) values in a list.

(2) compute the probability of a 6x heads or tails streak over all the samples

My amateur attempt:


import random

streaks=0
total=10000
reps=100

for experimentNumber in range(total):
    coin_flips=[]  # 1

    for j in range(reps):
        coin_flips.append(random.choice(['H','T']))
    repetition=1
    for i in range(1,len(coin_flips)):
        if coin_flips[i]== coin_flips[i-1]:
            repetition+=1
        else:
            repetition=1
        if repetition==6:    
            streaks+=1      
            break   


total_strks=(reps//6)*total

streaks_per=100*streaks/total_strks

print('Chance of streak: %s%%' % (streaks_per))
print(f'{streaks} of {total_strks}')

Problem: If a list contains 2 streaks or more in a row, they won't be calculated cuz of 'break' which make the interpreter get out of our third 'for' loop to the first one and then these remaining streaks get deleted (1)

Help me to fix it, If I'm right

  • I've given my answer on another thread that addresses this topic: https://stackoverflow.com/a/70176317/17555691 – tom_thumb_1 Nov 30 '21 at 21:46

1 Answers1

1

IT is easier to join all the flips of one experiment into a string and str.count() the streaks:

import random

def experiment(flips, streaksize):
    # generate a string of flips times H or T
    a = ''.join(random.choices("HT", k=flips))
    # count streaks
    streaks = a.count("H" * streaksize) + a.count("T" * streaksize)
    return streaks


total = 10000
reps = 100
streaksize = 6

streaks = 0
for _ in range(total):
    streaks += experiment(reps, streaksize)

print("You had ",streaks, "streaks of" ,streaksize, "consecutive H or T\nin", 
      total, "times", reps, "random head/tail experiments")

Output:

You had  15342 streaks of 6 consecutive H or T
in 10000 times 100 random head/tail experiments
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69