繁体   English   中英

如何在 Python 的上升序列中找到最长的连续子序列?

[英]How can I find the longest contiguous subsequence in a rising sequence in Python?

我需要在 Python 的上升序列中找到最长的连续子序列。

例如,如果我有A = [1, 2, 3, 5, 8, 9, 11, 13, 17, 18, 19, 20, 21, 25, 27, 28, 29, 30]

答案是[17, 18, 19, 20, 21]因为它是最长的连续子序列,有 5 个数字(而[1, 2, 3]3数字,而[27, 28, 29, 30]4数字长。)

我的代码陷入了无限循环

num_list = [1, 2, 3, 5, 8, 9, 11, 13, 17, 18, 19, 20, 21, 23, 25, 26, 27]
longest_sequence = {}
longest_sequence_length = 1
for num in num_list:
    sequence_length = 1
    while True:
        if (num + sequence_length) in num_list:
            sequence_length += 1
        else:
            if sequence_length > longest_sequence_length:
                longest_sequence_length_length = sequence_length
                longest_sequence = {"start": num, "end": num + (sequence_length - 1)}
        break
print(f"The longest sequence is {longest_sequence_length} numbers long"
      f" and it's between {longest_sequence['start']} and {longest_sequence['end']}")

您可以使用numpy来解决它:

import numpy as np
A=np.array(num_list)
max(np.split(A, np.where(np.diff(A) != 1)[0] + 1), key=len).tolist()

Output:

[17、18、19、20、21]

在第 13 行中,您需要一个 break 而不是 continue 语句。

此外,在第 11 行中,您犯了一个小错误,在变量名中添加了一个额外的“_length”。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM