Python ProgrammingPython Programming

How to find start and end index of longest sequence?

Longest sequence of 0

target = 0
A = [1, 2, 0, 0, 3, 4, 5, -1, 0, 2, -1, -3, 0, 0, 0, 0, 0, 0, 0, 0, 2, -3, -4, -5, 0, 0, 0]


def longest_seq(A, target):
    """ input list of elements, and target element, return longest sequence of target """
    cnt, max_val = 0, 0  # running count, and max count
    for e in A:
        cnt = cnt + 1 if e == target else 0  # add to or reset running count
        max_val = max(cnt, max_val)  # update max count
    return max_val


print(longest_seq(A, target))
8

Start and End position

A = [1, 2, 0, 0, 3, 4, 5, -1, 0, 2, -1, -3, 0, 0, 0, 0, 0, 0, 0, 0, 2, -3, -4, -5, 0, 0, 0]

count = 0
prev = 0
indexend = 0
for i in range(0, len(A)):
    if A[i] == 0:
        count += 1
    else:
        if count > prev:
            prev = count
            indexend = i
        count = 0

print("The longest sequence of 0's is " + str(prev))
print("index start at: " + str(indexend - prev))
print("index ends at: " + str(indexend - 1))
The longest sequence of 0's is 8
index start at: 12
index ends at: 19