For my CS 151 class, I made a program that simulates a given number of coin flips and determines the longest streak of heads and the longest streak of tails! There is likely a way to do this better, but I am quite happy with my solution. If you happen to be in this class with me, please follow the rules in the syllabus for academic integrity. No copying code and you must be able to explain every line.
# import statements
from random import randint
# function defintions
def flip():
r = randint(0,1)
if r == 1:
return 'H'
else:
return 'T'
def simulate(numFlips):
flips = []
for i in range(numFlips):
flips.append(flip())
return flips
def countStreak(flips):
headsStreak = 0
tailsStreak = 0
currentHeadsStreak = 0
currentTailsStreak = 0
lastFlip = flips[0]
for flip in flips:
if lastFlip == None:
lastFlip = flip
if flip == lastFlip and flip == 'H':
currentHeadsStreak += 1
if flip == lastFlip and flip == 'T':
currentTailsStreak += 1
if currentHeadsStreak > headsStreak:
headsStreak = currentHeadsStreak
if currentTailsStreak > tailsStreak:
tailsStreak = currentTailsStreak
elif flip != lastFlip and flip == 'H':
if headsStreak == 0:
headsStreak = currentHeadsStreak
currentHeadsStreak = 1
elif flip != lastFlip and flip == 'T':
if tailsStreak == 0:
tailsStreak = currentTailsStreak
currentTailsStreak = 1
lastFlip = flip
print(f"The longest streak of Heads was {headsStreak}\nThe longest streak of Tails was {tailsStreak}")
# Bonus
def countSix(flips):
lastFlip = flips[0]
headsStreak = 1
for flip in flips:
if lastFlip == None:
lastFlip = flip
if flip == lastFlip and flip == 'H':
headsStreak += 1
else:
headsStreak = 1
if headsStreak == 6:
return True
lastFlip = flip
return False
if __name__ == "__main__":
flips = simulate(100)
print(f"List of flips:\n{flips}")
countStreak(flips)
print(f"Count Six Heads: {countSix(flips)}")