I was trying to write a program that that counts the longest streak of heads in a random 100 coin toss, Able to print print out the toss result but I don't how to initialize the count for longest streak and go about it, Am new to programming and python
import random
total_heads = 0
count = 0
while count < 100:
coin = random.randint(1, 2)
if coin == 1:
print("H")
total_heads = 1
count = 1``
elif coin == 2:
print("T")
CodePudding user response:
This should do the trick:
import random
total_heads = 0
count = 0
longest_streak = 0
current_streak = 0
while count < 1000:
coin = random.randint(1, 2)
if coin == 1:
print("H")
total_heads = 1
current_streak = 1
count = 1
elif coin == 2:
print("T")
current_streak = 0
if current_streak > longest_streak:
longest_streak = count
print(longest_streak)
print(total_heads)
CodePudding user response:
from random import randint as r
heads_streaks = [0]
for i in range(100):
coin = r(0, 1)
if not coin:
print("H")
heads_streaks[-1] = 1
else:
print("T")
heads_streaks.append(0)
print("longest streak is: {}".format(sorted(heads_streaks, reverse=True)[0]))
CodePudding user response:
At the risk of too much magic, these are the tools I'd use:
random.choices()
can be used to draw your 100 samples in one stepitertools.groupby()
can be used to group these tosses into streaks, i.e. partition the random tosses into groups where the side is the same- list comprehensions and generators make it very easy to loop over things and pull out the information you want
Putting these together I get:
import random
import itertools
# perform 100 coin tosses and print them out
tosses = random.choices('HT', k=100)
print('tosses: ', *tosses)
# turn these into streaks of the same side
streaks = [''.join(streak) for _, streak in itertools.groupby(tosses)]
print('streaks: ', *streaks)
# get the longest streak of heads
lsh = max(len(s) for s in streaks if s[0] == 'H')
print('longest streak of heads: ', lsh)
One run of which outputs:
tosses: H T H T T T H H T T H H H H T H T T T T H T T H H H H H T T H H H H H H T T T T H T H H T H T T H H H H H H H T T T H T H H T T T H H T T H H T H T H H T H H H T T H T T H T H T H H T T T T T T H T H
streaks: H T H TTT HH TT HHHH T H TTTT H TT HHHHH TT HHHHHH TTTT H T HH T H TT HHHHHHH TTT H T HH TTT HH TT HH T H T HH T HHH TT H TT H T H T HH TTTTTT H T H
longest streak of heads: 7