-2

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

  • 1
    It seems like you are looking for the *maximum* count of `1` in a row, otherwise how do you account for the two additional `1` values at the end? Are you looking for the max? – Mark Dec 15 '20 at 03:01
  • Does this answer your question? [How can I count the occurrences of a list item?](https://stackoverflow.com/questions/2600191/how-can-i-count-the-occurrences-of-a-list-item) – Michael Butscher Dec 15 '20 at 03:01
  • 1
    @MichaelButscher That's total, not in a row. – superb rain Dec 15 '20 at 03:11

1 Answers1

2

Use groupby to group the identical items, and then find the max of the lens 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
Samwise
  • 68,105
  • 3
  • 30
  • 44