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 0
s 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