我正在尝试寻找列表中最长的递增连续子序列。
示例:如果我有一个列表:[1,2,3,0,2,3,5,6,7,1,4,5,6,9]
输出应该是 [0,2,3,5,6,7]
因为它比 [1,2,3]
和 [1,4,5, 6,9]
我已经编写了代码,可以将列表分成较小的列表(如上所示),但仅计算每个较小序列的长度。但我需要做的是输出最长的子序列而不是它的长度,出于某种奇怪的原因我似乎无法做到这一点(我不断收到逻辑错误)。
这是我的代码,这是我尝试实现它的一种方法,我面临的问题是将 temp
附加到 arr2
时。请帮我解决这个问题,并建议我可以使用一种替代且更有效的算法吗?
arr = [1,2,3,0,2,3,5,6,7,1,4,5,6,9] #original list
arr2 = [] #empty list (2 dimension)
counter = 1
temp = [] #temporary list
for x,y in enumerate(arr):
if(x == 0):
temp.append(y) #append first value to temp
else:
if(arr[x] > arr[x-1]): #if value of x is greater than previous one:
counter += 1 #increase counter if condition met
temp.append(y) #append list value to temp
else: #if value of x is not greater than previous one:
print(temp)
arr2.append(temp) #append entire temp list to arr2
temp[:] = [] #clear the temp list
temp.append(y) #append the new lowest value to temp
counter = 1 #reset counter
print(arr2)
最佳答案
首先,您在写入时复制对列表的引用:
arr2.append(temp)
然后,您更新列表 temp
,因此您最终会在 arr2
中获得对同一列表的多个引用。
您应该复制该列表:
arr2.append(temp[:])
此外,您永远不会复制找到的最后一个子序列,因此您在 arr2
中丢失了一个子序列。
您可以在 for
循环之外执行此操作,例如:
else: #if value of x is not greater than previous one:
print(temp)
arr2.append(temp) #append entire temp list to arr2
temp[:] = [] #clear the temp list
temp.append(y) #append the new lowest value to temp
counter = 1 #reset counter
arr2.append(temp[:])
print(arr2)
通过上述,您将得到[[1, 2, 3], [0, 2, 3, 5, 6, 7], [1, 4, 5, 6, 9]]
当您打印 arr2
时。
然后,只需选择里面最长的列表即可。
关于python - 连续递增子序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40479214/