python - 连续递增子序列

标签 python arrays list

我正在尝试寻找列表中最长的递增连续子序列。

示例:如果我有一个列表:[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/

相关文章:

python - 在 Django 中使用抽象多重继承时外键冲突

python - 我可以在没有根记录器的情况下拥有logging.ini 文件吗?

python - 替换作为参数传递的列表的内容

c# - 试图制作一个二维列表数组

java - Java hibernate中如何转换列表类型

python - 将结构体元胞数组从 Python 传递到 MATLAB

java - 如何在方法中输入数组作为参数?

java - 在java中从json数组生成Excel工作表报告

python - 显示基于元组的排序列表并在字典中循环

java - 检测 JSON 对象列表中的重复条目