Search code examples
pythonlistindices

Find starting and ending indices of list chunks satisfying given condition


I am trying to find the start and stop indices of chunks of positive numbers in a list.

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

For the given example input, the desired output is:

[(0, 2), (7, 9), (14, 17), (21, 25), (29, 30)]

Solution

  • How about using some flags to track where you are in the checking process and some variables to hold historical info?

    This is not super elegant code but it is fairly simple to understand I think and fairly robust for the use case you gave.

    My code

    cross = [7,5,8,0,0,0,0,2,5,8,0,0,0,0,8,7,9,3,0,0,0,3,2,1,4,5,0,0,0,7,5] 
    foundstart = False
    foundend = False
    startindex = 0
    endindex = 0
    for i in range(0, len(cross)):
        if cross[i] != 0:
            if not foundstart:
                foundstart = True
                startindex = i
        else:
            if foundstart:
                foundend = True
                endindex = i - 1
    
        if foundend:
            print(startindex, endindex)
            foundstart = False
            foundend = False
            startindex = 0
            endindex = 0
    
    if foundstart:
        print(startindex, len(cross)-1)
    

    Output

    0 2
    7 9
    14 17
    21 25
    29 30