Nikita Gupta Nikita Gupta - 3 months ago 13
Python Question

Find longest sequence of 0's in the integer list


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)

which return 8 as the max length.

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


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