在数组Python中查找增加和减少的子序列

时间:2018-04-23 16:26:06

标签: python subsequence

我有一个复杂的问题。

我有这个数组[34,33,5,78,50,76,82,95,119,31,49,76],我需要找到所有最长的增加和减少的子序列。 例如,您可以找到的最长的减少子序列的长度为3。然后,我需要找到所有长度的子序列,例如:[78,76,76]或[78,50,31]或[34,33,31]等。

我一直试图在python中创建一个算法,在输入中给定一个数组,它会返回所有最长的递减和递增的子序列,但是我无法成功。 到目前为止我已写过这个,

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

但它不起作用 你可以帮助我吗?

感谢您的关注。

1 个答案:

答案 0 :(得分:1)

如果我理解你的问题,我做过类似的事情。

我的代码可以查找数字列表中所有可能的减少数字。

我将尝试解释它(仅用于减少序列):

我的方式是:

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

现在解释逻辑并不容易,但理解阅读代码并不难。如果您有任何疑问,可以提出要求,我可以稍后发布更多时间的解释。

但是使用此功能,可以轻松过滤最大的:

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

对于您的输入,我得到的答案是:

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

对于增加序列,很容易更改代码(只需更改> = to< =应该这样做)。

希望我能帮到你。