Longest run/island of a number in Python

后端 未结 2 1574
孤独总比滥情好
孤独总比滥情好 2021-01-22 05:07

I have an array with 0\'s repeating multiple times but I want to find the longest set of 0s. For example:

myArray= [[1,0],[2,0],[3,0][4,0][5,1][6,0][7,0][8,0][9,         


        
2条回答
  •  甜味超标
    2021-01-22 05:14

    You can start by numbering the consecutive elements in a for loop and then simply get the index of the maximum value.

    >>> cv, a = [], 0
    >>> for x in myArray:
    >>>     if x[1] == 0:
    >>>         a += 1
    >>>     else:
    >>>         a = 0
    >>>     cv.append(a)
    >>> print(a)
    [1, 2, 3, 4, 0, 1, 2, 3, 4, 5, 6, 7, 0, 0, 1, 2, 3, 4, 0, 1]
    
    >>> mi = cv.index(max(cv))  # finds index of *first* maximum
    >>> run = [mi - cv[mi] + 1, mi]
    >>> print(run)
    [5, 11] 
    

提交回复
热议问题