+ 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

6th Jan 2022, 3:47 PM
Hojiakbar
Hojiakbar - avatar
5 odpowiedzi
+ 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
6th Jan 2022, 6:30 PM
Lothar
Lothar - avatar
+ 8
Like this? n is a streak print(n*'T' in ''.join(mainList))
6th Jan 2022, 4:02 PM
Lisa
Lisa - avatar
+ 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
6th Jan 2022, 4:27 PM
Elon
Elon - avatar
+ 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]]
6th Jan 2022, 4:10 PM
Bartek
+ 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 :)
7th Jan 2022, 7:23 AM
Hojiakbar
Hojiakbar - avatar