Highest Number Of A Certain Consecutively Repeating Value In A List
I'm sorry the title is confusing, but I couldn't word it any better. So, let's say I have this list: My_list = [1,1,1,0,0,0,1,1,1,1,0,0] How do display the highest number of conse
Solution 1:
A simple solution, probably something more elegant in itertools somewhere.
x =[1,1,1,0,0,0,1,1,1,1,0,0,0,0,0]
d ={}c= x[0]
c_cnt =1for i in x[1:]:if i ==c:
c_cnt +=1else:
d[c]=max(d.get(c,0),c_cnt)c=i
c_cnt=1
d[c]=max(d.get(c,0),c_cnt)
print(d)
Solution 2:
Similar previous problem searching would find
from itertools import groupby
mylist = [1,1,1,0,0,0,1,1,1,1,0,0]
#count_ones = (max(list(group), for _, group in groupby(mylist)), len)
runs = [list(group) for _, group in groupby(mylist)] #create sublists of same values (ones of zeros)
ones = [g for g in runs if g[0] == 1] # ones only sublists
zeros = [g for g in runs if g[0] == 0] # zeros only sublistsprint(len(max(ones,key=len))) # max sublists of ones -> 4print(len(max(zeros,key=len))) # max sublists of zeros -> 3
Solution 3:
Just to be in general case not just 1 or 0
:
from itertools import groupby
My_list = [1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0]
result = {}
for element, groups in groupby(My_list):
count = sum(1for _ in groups)
if element in result:
if count > result[element]:
result[element] = count
else:
result[element] = count
for e, count in result.items():
print('longest chains for {} is {}'.format(e, count))
OUTPUT:
longest chains for1is4
longest chains for0is3
I tried to keep the code simple to understand the logic.
Solution 4:
I have some code that does it. I'm not sure if this is the best approach for very long lists, but it should work for the list you posted.
ps. No numpy :)
defunique(list1):
# intilize a null list
unique_list = []
# traverse for all elements for x in list1:
# check if exists in unique_list or not if x notin unique_list:
unique_list.append(x)
# print list return unique_list
My_list = [1,1,1,0,0,1,1,1,1,1,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1]
#Create an array with the unique values from your list
unique_list = unique(My_list)
#Create a list with size = amount of unique values
zeros = [0for _ inrange(len(unique_list))]
count = 1for i inrange(0,len(My_list)-1):
#Is the following consecutive value equal to the current value? if (My_list[i] == My_list[i+1]) and (i != len(My_list)-2):
#count how many consecutive repetitions you have
count = count + 1else:
idx = unique_list.index(My_list[i])
#If it's the highest amount of repetitions, save itif zeros[idx] < count:
zeros[idx] = count
count = 1for i inrange(0, len(unique_list)):
print("Highest consecutive "+ str(unique_list[i]) + "'s are: " + str(zeros[i]))
Post a Comment for "Highest Number Of A Certain Consecutively Repeating Value In A List"