I am struggling with the solution of the 'Coin Flip' practice project at the end of chapter 4 in 'Automate the boring stuff' for python programming.
I have two solutions, both yielding a totally different result (first one is clearly false). I am not sure, what is the right solution to the answer.
Solution 1:
import random
nextFlip = []
numberOfStreaks = 0
# Code that creates a list of 10000 'heads' or 'tails' values.
for expNum in range(10000):
select = random.randint(0,1)
if select == 0:
nextFlip.append('H')
elif select == 1:
nextFlip.append('T')
# Code that checks if there is a streak of 6 heads or tails in a row.
for i in range(0,(len(nextFlip)-6)):
if nextFlip[i] == nextFlip[i 1] == nextFlip[i 2] == nextFlip[i 3] == nextFlip[i 4] == nextFlip[i 5] != nextFlip[i 6]:
numberOfStreaks =1
print('Chance of streak: %s%%' % ((numberOfStreaks / 10000)*100))
Solution 2:
import random
nextFlip = []
hlist = 0
tlist = 0
numberOfStreaks = 0
# Code that creates a list of 10000 'heads' or 'tails' values.
for expNum in range(10000):
select = random.randint(0,1)
if select == 0:
nextFlip.append('H')
elif select == 1:
nextFlip.append('T')
# Code that checks if there is a streak of 6 heads or tails in a row.
for i in range(0,(len(nextFlip)-6)):
if nextFlip[i] == 'H':
hlist = 1
if hlist == 6:
numberOfStreaks =1
elif nextFlip[i] == 'T':
tlist = 1
if tlist == 6:
numberOfStreaks =1
print('Chance of streak: %s%%' % ((numberOfStreaks / 10000)*100))
Maybe someone can help me and tell me what I did wrong.
CodePudding user response:
This seems to work:-
import random
N = 10_000
S = 6
HEAD = 'H'
TAIL = 'T'
T = [HEAD if random.randint(0, 1) else TAIL for _ in range(N)]
c = T[0]
s = 1
STREAKS = 0
for t in T[1:]:
if t == c:
s = 1
if s == S:
STREAKS = 1
s = 0
else:
c = t
s = 1
print(STREAKS)
CodePudding user response:
You could generate the random flips using a comprehension and store it in a string to make processing of the streaks easier. Since streaks can overlap, you need to examine subranges starting at every position:
flips = "".join(random.choice("HT") for _ in range(1000))
streaks = sum(flips[i:i 6] in ('HHHHHH','TTTTTT') for i in range(1000))
The sum() function will convert boolean values to 1 or zero (True is 1), so adding up the result of the streak conditions produces the total.