+ 2
How to check if an item has a streak of n times in a list?
Given 100 random 'H'(heads) and 'T'(tails) in a list, how can we check if an item has a streak of n times? I mean, if 'T' occurs this way: ['T', 'T', 'T', 'T', 'T', 'T', 'H', 'H',], it has a streak of 6 times, while H would have 2 I got stuck at this; can you help me? The code below generates a list of 100 Ts and Hs. https://code.sololearn.com/cZQanX2uihd0/?ref=app
5 ответов
+ 9
Hojiakbar ,
[edited] pythons module *itertools* with its method: *groupby* can also be used to do this task:
from itertools import groupby
inp = "HHHTTHTTT".replace(' ','') #removed spaces before applying groupby
print([{k:len(list(v))} for k,v in groupby(inp)]) # use a comprehension to create a dict
the result is: [{'H': 3}, {'T': 2}, {'H': 1}, {'T': 3}]
# more informations about groupbyy:
# https://docs.python.org/3/library/itertools.html?highlight=groupby#itertools.groupby
+ 8
Like this? n is a streak
print(n*'T' in ''.join(mainList))
+ 4
ef getStreaks(listelmts, el):
"""This function return all n_streaks of an element in the given list
return a list []
"""
all_streaks = []
curr_streak = 0
for i in range(len(listelmts) - 1):
if listelmts[i] == el:
curr_streak = curr_streak + 1
if i == len(listelmts):
break
if listelmts[i+1] == el:
continue
else:
all_streaks.append(curr_streak)
curr_streak = 0
return all_streaks
def hasStreak(el, numStreack, listelmts):
""" This function check if an element as a given number of streak in a given arrah
it use the getStreaks function
retun a boolean
"""
if numStreack in getStreaks(listelmts, el):
return True
return False
https://code.sololearn.com/cqJjEEM7kBg0/?ref=app
+ 3
Add this at the end of your code
count=[]
for i in mainList:
if len(count)==0:
count.append([i,1])
elif count[len(count)-1][0]==i:
count[len(count)-1][1]+=1
elif count[len(count)-1][0]!=i:
count.append([i,1])
print(count)
after this code run count will be array of arrays with type and count in streak eg.
[['H', 3], ['T', 6], ['H',2]]
+ 1
Lothar
Wow, in my opinion it is by far the most convenient and reliable solution. That's a great library to use in such situations.
Thank you all for your help :)