【问题标题】:Find increasing and decreasing subsequence in an array Python在数组Python中查找递增和递减子序列
【发布时间】:2018-04-23 16:26:05
【问题描述】:

我有一个有点复杂的问题。

我有这个数组 [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

但它不起作用 你能帮帮我吗?

感谢您的关注。

【问题讨论】:

  • 你有什么尝试吗?你能发布你迄今为止最好的代码吗?有了它,我们可以帮助您了解它为什么不起作用并可能修复它......

标签: python subsequence


【解决方案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]]

对于增加序列,很容易更改代码(只需将 >= 更改为

希望我能帮上忙。

【讨论】:

    猜你喜欢
    • 2012-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-29
    相关资源
    最近更新 更多