Salman Fazal Salman Fazal - 29 days ago 8
Python Question

consecutive increasing subsequence

I'm am trying to look for the longest increasing consecutive sub-sequence in a list.

example: if I have a list:

[1,2,3,0,2,3,5,6,7,1,4,5,6,9]
the output should be
[0,2,3,5,6,7]
as it's longer than
[1,2,3]
and
[1,4,5,6,9]


I have written my code where I can break my list into smaller lists (as shown above) but only calculate the length of each smaller sequence. But what I need to do is output the longest sub-sequence and not its length, for some weird reason I just cannot seem to be able to do that (I keep getting logical errors).

So here's my code and this is one way I tried to implement it, the problem I am facing is when appending
temp
to
arr2
. Please help me fix this and do suggest an alternative and more efficient algorithm I could use for this?

arr = [1,2,3,0,2,3,5,6,7,1,4,5,6,9] #original list
arr2 = [] #empty list (2 dimension)
counter = 1

temp = [] #temporary list
for x,y in enumerate(arr):

if(x == 0):
temp.append(y) #append first value to temp
else:

if(arr[x] > arr[x-1]): #if value of x is greater than previous one:

counter += 1 #increase counter if condition met
temp.append(y) #append list value to temp

else: #if value of x is not greater than previous one:

print(temp)
arr2.append(temp) #append entire temp list to arr2
temp[:] = [] #clear the temp list
temp.append(y) #append the new lowest value to temp
counter = 1 #reset counter

print(arr2)

Answer

First, you are copying a reference to the list when you write:
arr2.append(temp)
And you then update the list temp, so you end up with several references to the same list in arr2. You should make a copy of the list instead:
arr2.append(temp[:])

Also, you never copy the last subsequence found so you are missing one in arr2. You can do it outside of the for loop for example:

        else: #if value of x is not greater than previous one:

            print(temp)
            arr2.append(temp) #append entire temp list to arr2
            temp[:] = [] #clear the temp list
            temp.append(y) #append the new lowest value to temp
            counter = 1 #reset counter

arr2.append(temp[:])
print(arr2)

With the above, you will get [[1, 2, 3], [0, 2, 3, 5, 6, 7], [1, 4, 5, 6, 9]] when you print arr2. Then, it is only a matter of selecting the longest list inside.