Reputation: 11
I am writing a script that watches an online coin flip game, and keeps a tally of the results. I would like to find a simpler way of finding out how many times the streak ended after three of the same results, four of the same result etc.
if result = heads:
headsCount += 1
headsStreak +=1
tailsCount = 0
tailsStreak = 0
headsCount is the total amount of heads results witnessed in a session, and the streak is just so I can display how many heads have appeared in a row. This is update by:
if headsCount >= headsStreak:
headsStreak = headsCount
My problem - I wish to keep track of how many times the streak ends at one, ends at two, ends at three etc...
A silly way I have for now:
if headsStreak = 1:
oneHeadsStreak +=1
if headsStreak = 2
twoHeadsStreal +=1
But it is very tedious. So is there an easier way to create the variables... for example:
for i in range (1, 20):
(i)streak = 0
and then something like
for i in range (1, 20):
if headsStreak = i:
(i)streak += 1
Thank you in advance!
Upvotes: 1
Views: 262
Reputation: 43320
Using a defaultdict, You just need three variables,
from collections import defaultdict
current_streak = 0
current_side = "heads"
streak_changes = defaultdict(int)
Then store the values in a dictionary when the streak changes
if side == current_side:
current_streak += 1
else:
current_side = side
streak_changes[current_streak] += 1
current_streak = 1
Upvotes: 0
Reputation: 606
You could use a list to keep track of the streak counter. You will have to think about which index is which streak length (e.g. index 0 is for streak length 1, index 1 for length 2 etc.).
Initialize all list elements to zero:
l = [0 for i in range(20)]
Then, whenever a streak ends, increment the list element at the corresponding index: l[3] += 1
for a 4-streak.
Upvotes: 1