How can I write a algorithm that finds how many of a certain number is in a row in a list in python?
FOR EXAMPLE:
Input: List = [0,1,1,1,0,1,1] N = 1
Output: 3
How can I write a algorithm that finds how many of a certain number is in a row in a list in python?
FOR EXAMPLE:
Input: List = [0,1,1,1,0,1,1] N = 1
Output: 3
Use groupby
to group the identical items, and then find the max
of the len
s of the groups where the item equals N
:
>>> from itertools import groupby
>>> max(len(list(group)) for i, group in groupby([0, 1, 1, 1, 0, 1, 1]) if i == 1)
3
>>> max(len(list(group)) for i, group in groupby([0, 1, 1, 1, 0, 1, 1]) if i == 0)
1