Here's the problem from the book Automate the boring stuff:
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.
The #comments
are a hint by the author. This program I created ran just fine but the chance of streak is surprisingly high to me: ~152% - 153%. So I'm wondering if I got the logic right? Any help will be greatly appreciated.
import random
def flip():
random_num = random.randint(0, 1)
if random_num == 1:
return "H"
else:
return 'T'
numberOfStreaks = 0 #author wrote this line
for experimentNumber in range(10000): #author wrote this line
# Code that creates a list of 100 'heads' or 'tails' values.
head_tail_str = ""
side = flip()
head_tail_str += side
for _ in range(99):
prev_side = side
side = flip()
if side != prev_side:
head_tail_str += f",{side}"
else:
head_tail_str += side
# Code that checks if there is a streak of 6 heads or tails in a row.
head_tail_lst = head_tail_str.split(',')
for item in head_tail_lst:
if len(item) >= 6:
numberOfStreaks += (int(len(item)) // 6)
print('Chance of streak: %s%%' % (numberOfStreaks / 100)) #author wrote this line
P.S. I've been learning Python for 1 month