You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python确定列表中需移除元素,使剩余序列单调?

问题:找出数字列表中需移除的元素以得到单调序列

我需要解决的问题是:如何找出数字列表中需要移除的元素,使剩余序列成为单调序列(使用最新Python版本)。具体示例如下:

  • 列表[1,1,2,1,1,1]:现有算法能识别序列非单调,且最长单调子序列为[1,1,1],但实际只需移除元素2,整个序列就会单调。
  • 列表[1,2,3,0,0,0,4,5,6]:现有算法找到的最长单调子序列是[0,4,5,6],但移除中间3个0可得到更长的单调序列。

暴力法实现效率极低,因此寻求高效解决方案。以下是我当前的代码:

# tablica是波兰语中“数组”的意思,指我们要测试的整数列表
# max_list是列表中最长单调子序列的长度
# current_list是程序当前正在检查的子序列
# type:当前子序列的单调类型
# ftype:整个列表的单调类型

tablica = []
for i in range(6):
    n = int(input())
    tablica.append(n)

def mono(tablica):
    current_list = []
    max_list = []

    type = 0
    ftype = 0
    for i in range(-1, len(tablica)):
        print(f'{i+1}:')
        if tablica[i-1] == tablica[i]:
            if type == 0 or type == 1:
                type = 1
                current_list.append(tablica[i])
            else:
                ftype = -1
                if len(max_list) < len(current_list):
                    max_list = current_list.copy()
                type = 0
                current_list.clear()
                current_list.append(tablica[i])
            print(current_list, max_list)

        elif tablica[i-1] < tablica[i]:
            if type == 0 or type == 2:
                type = 2
                current_list.append(tablica[i])
            else:
                ftype = -1
                if len(max_list) < len(current_list):
                    max_list = current_list.copy()
                type = 0
                current_list.clear()
                current_list.append(tablica[i])
            print(current_list, max_list)

        elif tablica[i-1] > tablica[i]:
            if type == 0 or type == 3:
                type = 3
                current_list.append(tablica[1])  # 此处疑似笔误,应为tablica[i]
            else:
                ftype = -1
                if len(max_list) < len(current_list):
                    max_list = current_list.copy()
                type = 0
                current_list.clear()
                current_list.append(tablica[i])
            print(current_list, max_list)

    if len(max_list) < len(current_list):
        max_list = current_list.copy()
    if ftype == 0:
        ftype = type

    return ftype, len(max_list), max_list

print(mono(tablica))

内容的提问来源于stack exchange,提问作者krzychu_Pyth0n

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 14:41:23