在数组中查找递增和递减的子序列 Python
Find increasing and decreasing subsequence in an array Python
我有一个有点复杂的问题。
我有这个数组 [34,33,5,78,50,76,82,95,119,31,49,76],我需要找到所有最长的递增和递减子序列。
例如,您可以找到的最长递减子序列的长度为 3。然后,我需要找到所有具有该长度的子序列,例如:[78,76,76] 或 [78,50,31] 或 [34,33,31] 等..
我一直在尝试在 python 中创建一个算法,给定一个输入数组,它 returns 所有最长的递减和递增子序列,有一段时间但我做不到成功。
到目前为止,我已经写完了,
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
但是没用
你能帮帮我吗?
感谢您的关注。
好吧,如果我正确理解你的问题的话,我做过一次类似的事情。
我的代码用于查找数字列表中所有可能递减的数字。
我将尝试解释它(只是为了减少序列):
我的做法是:
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
现在解释逻辑并不容易,但阅读代码理解起来并不难。如果您有任何疑问,可以提问,我可以post稍后再解释。
但是有了这个功能,ow就很容易筛选出最大的了:
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]]
对于递增序列,更改代码很容易(只需将 >= 更改为 <= 即可)。
希望我有所帮助。
我有一个有点复杂的问题。
我有这个数组 [34,33,5,78,50,76,82,95,119,31,49,76],我需要找到所有最长的递增和递减子序列。 例如,您可以找到的最长递减子序列的长度为 3。然后,我需要找到所有具有该长度的子序列,例如:[78,76,76] 或 [78,50,31] 或 [34,33,31] 等..
我一直在尝试在 python 中创建一个算法,给定一个输入数组,它 returns 所有最长的递减和递增子序列,有一段时间但我做不到成功。 到目前为止,我已经写完了,
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
但是没用 你能帮帮我吗?
感谢您的关注。
好吧,如果我正确理解你的问题的话,我做过一次类似的事情。
我的代码用于查找数字列表中所有可能递减的数字。
我将尝试解释它(只是为了减少序列):
我的做法是:
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
现在解释逻辑并不容易,但阅读代码理解起来并不难。如果您有任何疑问,可以提问,我可以post稍后再解释。
但是有了这个功能,ow就很容易筛选出最大的了:
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]]
对于递增序列,更改代码很容易(只需将 >= 更改为 <= 即可)。
希望我有所帮助。