user6820366 - 4 months ago 40

Python Question

I wanted to find the longest decreasing sub sequence inside a given list for example L = [1, 2, 1, 2, 1, 2, 1, 2, 1], the result should be [2,1] however I cant seem to produce that result. Can someone tell me why it doesn't work ? The output is something [0,2,1,2,1,2,1,2,1] Nevermind the first zero but the result should produce [2,1].

Here's a code I tried

`L = [1, 2, 1, 2, 1, 2, 1, 2, 1]`

current = [0]

smallest = []

for i in range(len(L)):

if i < (len(L)-1):

if L[i] >= L[i+1]:

current.append(L[i])

else :

if L[i] < current[-1]:

current.append(L[i])

elif i>= (len(L)-1):

if L[-1]<L[i-1]:

current.append(L[i])

else:

current = [i]

if len(current) > len(smallest):

smallest = current

Result : [0,2,1,2,1,2,1,2,1]

Desired Result : [2,1]

Answer

when you say `current = [0]`

, it actually adds `0`

to the list, maybe you want `current = [L[0]]`

.

See this:

```
def longest_decreasing_sublist(a):
lds, current = [], [a[0]]
for val in a[1:]:
if val < current[-1]: current.append(val)
else:
lds = current[:] if len(current) > len(lds) else lds
current = [val]
lds = current[:] if len(current) > len(lds) else lds
return lds
L = [1, 2, 1, 2, 1, 2, 1, 2, 1]
print (longest_decreasing_sublist(L))
# [2, 1]
```