我有一个复杂的问题。
我有此阵列[34,33,5,78,50,76,82,95,119,31,49,76],我需要找到所有最长的增加和减少的子序列。例如,最长的降低子序列您可以发现的Lenght为三个。然后,我需要找到所有的lenght,例如:[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
但是它不起作用你可以帮我吗?
感谢您的关注。
,如果我正确理解您的问题,我曾经做过类似的事情。
我的代码可以在数字列表中找到所有可能的减少数字。
我将尝试解释它(仅用于减少序列(:
我的方式是:
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
现在解释逻辑并不容易,但是了解读取代码并不难。如果您有任何疑问,您可以问,我可以在以后发布更多的解释。
但是,通过此功能,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]]
对于增加序列,更容易更改代码(只需更改> = to< =应该这样做(。
希望我有帮助。