繁体   English   中英

Python 程序 - 在给定数字列表中查找最大序列的程序

[英]Python Program - program to find largest sequence in a given list of numbers

我需要设计一个 python 程序,它输出给定数字列表中的最大序列。

例如,

INPUT = [1,2,3,2,4,5,6,7,8,1,0,4,5,6]

预期结果:

[4, 5, 6, 7, 8]

有人可以帮我写代码吗?

你可以做

from itertools import groupby
from operator import itemgetter

new_l = []
for k, g in groupby(enumerate(data), lambda ix : ix[0] - ix[1]):
    new_l.append(list(map(itemgetter(1), g)))

print(max(new_l, key=lambda x: len(x)))

输出:

[4, 5, 6, 7, 8]

一种不使用内置 python 模块且代码复杂度为 O(n) 的方法

a = [1,2,3,2,4,5,6,7,8,1,0,4,5,6]

large_seq = []
large_seq_len = 0
temp_seq = []
temp_seq_len = 0
x = None

for i in a:
    if x is None or x + 1 == i:
        temp_seq.append(i)
        temp_seq_len += 1
    else:
        if temp_seq_len > large_seq_len:
            large_seq = temp_seq
            large_seq_len = temp_seq_len
        temp_seq = [i]
        temp_seq_len = 1
    x = i

if temp_seq_len > large_seq_len:
    large_seq = temp_seq

print(large_seq)

https://www.online-python.com/XNjaLm9vMS

Sociopath 的答案可以折叠成一个相对较短的单行字

$ python
Python 3.7.7 (default, May  7 2020, 21:25:33) 
[GCC 7.3.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from itertools import groupby as g
>>> d, e, l, λ, m = [1,2,3,2,4,5,6,7,8,1,0,4,5,6], enumerate, len, list, max
>>> [i[1]for i in m((λ(s)for k,s in g(e(d),lambda j:j[0]-j[1])),key=lambda j:l(j))]
[4, 5, 6, 7, 8]
>>> 

暂无
暂无

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

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