Skip to content
Advertisement

Find longest sequence of 0’s in the integer list

A = [1,2,0,0,3,4,5,-1,0,2,-1,-3,0,0,0,0,0,0,0,0,-2,-3,-4,-5,0,0,0]

Return initial and ending index of longest sequence of 0‘s in the list. As, longest sequence of 0‘s in above list is 0,0,0,0,0,0,0,0 so it should return 12,19 as starting and ending index.Please help with some one line python code.

I tried :

k = max(len(list(y)) for (c,y) in itertools.groupby(A) if c==0)
print(k)

which return 8 as the max length.

Now, how to find start and end index of longest sequence?

Advertisement

Answer

you can first use enumerate to zip the item with index,

and then itertools.groupby(list,operator.itemgetter(1)) to group by item,

filter only 0s using list(y) for (x,y) in list if x == 0,

and at last max(list, key=len) to get the longest sequence.

import itertools,operator
r = max((list(y) for (x,y) in itertools.groupby((enumerate(A)),operator.itemgetter(1)) if x == 0), key=len)
print(r[0][0]) # prints 12
print(r[-1][0]) # prints 19
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement