簡體   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