[英]How can I find the longest contiguous subsequence in a rising sequence in Python?
I need to find the longest contiguous subsequence in a rising sequence in Python.我需要在 Python 的上升序列中找到最长的连续子序列。
For example if I have A = [1, 2, 3, 5, 8, 9, 11, 13, 17, 18, 19, 20, 21, 25, 27, 28, 29, 30]
例如,如果我有
A = [1, 2, 3, 5, 8, 9, 11, 13, 17, 18, 19, 20, 21, 25, 27, 28, 29, 30]
The answer would be [17, 18, 19, 20, 21]
because it's the longest contiguous subsequence with 5 numbers (whereas [1, 2, 3]
is 3
numbers long and [27, 28, 29, 30]
is 4
numbers long.)答案是
[17, 18, 19, 20, 21]
因为它是最长的连续子序列,有 5 个数字(而[1, 2, 3]
是3
数字,而[27, 28, 29, 30]
是4
数字长。)
My code is stuck in an endless loop我的代码陷入了无限循环
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']}")
You can use numpy
to solve it in one line:您可以使用
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: Output:
[17, 18, 19, 20, 21] [17、18、19、20、21]
In line 13 you need a break instead of a continue statement.在第 13 行中,您需要一个 break 而不是 continue 语句。
Also, in line 11 you had a little mistake, added an extra "_length" to you variable name.此外,在第 11 行中,您犯了一个小错误,在变量名中添加了一个额外的“_length”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.