You can use itertools.groupby
and max
:
>>> from itertools import groupby
def solve(strs):
return max((list(g) for k, g in groupby(strs, key=lambda x:int(x)%2) if not k),
key=len)
...
>>> solve('2456890048') #or pass `str(2456890048)` if you've integers.
['0', '0', '4', '8']
>>> solve('245688888890048')
['6', '8', '8', '8', '8', '8', '8']
Here:
[list(g) for k, g in groupby('2456890048', key=lambda x:int(x)%2) if not k]
returns:
[['2', '4'], ['6', '8'], ['0', '0', '4', '8']]
Now we can apply max
on this list(with key=len
) to get the longest sequence. (Note that in the original code I am using a generator expression with max
, so the list is not created in the memory.)