-2

I have a little complicated problem.

I have this array [34,33,5,78,50,76,82,95,119,31,49,76] and I need to find all the longest increasing and decreasing subsequences. For example, the longest decreasing subsequence you can find has a lenght of three. Then, I need to find all the subsequence with that lenght, e.g: [78,76,76] or [78,50,31] or [34,33,31] etc..

I've been trying to create an algorithm in python that, given an array in input, it returns all the longest decreasing and increasing subsequences, for a while but I couldn't succeed. I've written this so far,

def find_decreasing(seq):
found=[]
for v in seq[:-1]:        
    for iv in found[:]:
        if v > iv[0]:
            found.append([v+1]+iv)
    found.append([v])
return found

But it doesn't work May you help me?

Thanks for your attention.

Frank
  • 125
  • 1
  • 2
  • 8
  • Did you try anything? Can you please post your best code so far? With that we can help you understand why it is not working and maybe fix it... – DSLima90 Apr 23 '18 at 16:58

1 Answers1

1

Well i did something similar once, if i understood your question correctly.

My code works to find all possible decreasing numbers within a list of numbers.

I am going to try to explain it (just for decreasing sequences):

The way i did was:

def find_decreasing(seq):
    found=[]
    for v in seq[::-1]:        
        for iv in found[:]:
            if v >= iv[0]:
                found.append([v]+iv)
        found.append([v])
    return found

It is not easy to explain the logic now but it is not that hard to understanding reading the code. If you have any doubt, you can ask and I can post an explanation with more time later.

But with this function, ow it is easy to filter for the largest:

decreasing = find_decreasing(seq) # Find all decreasing
max_len = max(map(len,decreasing)) # get the max length of that sequences
final_list = list(filter(lambda a: len(a)==max_len, decreasing)) # filter the ones with the max length

For your input, the answer i get is:

final_list = [[78, 76, 76],
 [78, 76, 49],
 [78, 76, 31],
 [78, 50, 49],
 [78, 50, 31],
 [34, 33, 31],
 [34, 33, 5]]

For increasing sequences it is easy to change the code (just changing >= to <= should do it).

Hope I helped.

DSLima90
  • 2,680
  • 1
  • 15
  • 23