Find the start and end indices of values ​​greater than 0 in the list

I am trying to find the start and end index of numbers> 0 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] 

I get value indices> 0 followed by value index = 0.

Desired conclusion:

(0 2),(7 9), (14 17)..

Actual conclusion:

(2 3), (7 8)..

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)   
for i in range(0,len(cross)): 
    if cross[i]==0:
        while(cross[i-1]>0):
            i+=1
            print(i-1,i)  
-4
source share
1 answer

How about using some flags to keep track of where you are in the process of checking, and some variables to store historical information?

This is not very elegant code, but it is quite easy to understand, I think, and reliable enough for the case you are using.

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
+1
source

Source: https://habr.com/ru/post/1693366/


All Articles