Home > Mobile >  How to print first and last index of the longest sequence of same-values neighbors?
How to print first and last index of the longest sequence of same-values neighbors?

Time:02-11

I am interested in finding the first and last index of the longest sequence of same-valued neighbours for a given list. The closest question I could find was: First and last index of a sequence, but this does not exactly answer my question.

So let's say for example:

a = [4, 6, 1, 0, 0, 0, 2, 4, 4, 1]

I would like to output to be

[3, 5]

Here is what I have come up with so far, and it works for this example. However, once the list changes to have a 0 somewhere before or after the sequence (non-neighbouring) it does not work anymore.

# Find distinct values of a
distinct = []
for x in a:
    if x not in distinct:
        distinct.append(x)
# Check which value has the longest sequence
countMax = 0
countNow = 1
num = 0
for i in a:
    if a[i] == a[i 1]:
        countNow  = 1
        num = i
    else:
        countNow = 1
    if countNow > countMax:
        countMax = countNow
longest = distinct[num-1]
# Find first index value of number with longest sequence
firstIndex = a.index(longest)
# Find last index value of number with longest sequence
a_reverse = a[::-1]
firstIndex_reverse = a_reverse.index(longest)
lastIndex = len(a) - 1 - firstIndex_reverse

print(firstIndex, lastIndex)

I don't know how better to find the first and last index for only the sequence in question.

CodePudding user response:

I'd just iterate the list and keep track of everything:

a = [4, 6, 1, 0, 0, 0, 2, 4, 4, 4, 4, 4, 4, 1]

# indices
best_start = 0
best_end = 0
curr_start = 0
curr_end = 0

prev_val = a[0]

for (idx, curr_val) in enumerate(a[1:]):
    curr_end = idx   1 #  1 since slicing shifted everything
    if prev_val == curr_val:
        if curr_end - curr_start > best_end - best_start:
            best_start = curr_start
            best_end = curr_end
    else:
        curr_start = curr_end
    prev_val = curr_val

print(best_start, best_end)
  • Related