簡體   English   中英

Python中最長的不同連續列表

[英]Longest distinct consecutive list in Python

我有一個清單:

a = [2, 3, 5, 6, 6, 7, 10, 11, 13, 14, 15, 16, 16, 17, 18, 20, 21]

是否有可能創建一個顯示最長的不同連續元素列表的函數?

請展示如何做到這一點

在這種情況下,答案應該是:

13, 14, 15, 16, 17, 18

假設您的列表已排序:

>>> from itertools import groupby
>>> z = zip(a, a[1:])
>>> tmp = [list(j) for i, j in groupby(z, key=lambda x: (x[1] - x[0]) <= 1)]
>>> max(tmp, key=len)
[(13, 14), (14, 15), (15, 16), (16, 16), (16, 17), (17, 18)]
>>> list(range(_[0][0], _[-1][-1]+1))
[13, 14, 15, 16, 17, 18]

ETA:修復最后一步;

最簡單的做法似乎是遍歷列表一次,構建您可以找到的任何序列,然后打印最長的序列。

a = [2, 3, 5, 6, 6, 7, 10, 11, 13, 14, 15, 16, 16, 17, 18, 20, 21]

seqlist = [] # List of Sequences
seq = []     # Current Sequence
last = -1

for item in a:
   # Start a new sequence if the gap from the last item is too big
   if item - last > 1:
       seqlist.append(seq)
       seq = []

   # only add item to the sequence if it's not the same as the last
   if item != last:
        seq.append(item)

   last = item

# Print longest sequence found
print max(seqlist)

可能有更多的pythonic方式,但我現在想不到它,所以這里有一個非常基本的解決方案:

def longestDistinctConsecutiveList ( lst ):
    lst = list( set( lst ) ) # get rid of duplicated elements
    lst.sort() # sort

    s, l = 0, 0
    for i in range( len( lst ) ):
        for j in range( i, len( lst ) ):
            if lst[j] - lst[i] == len( lst[i:j] ) > l:
                l = 1 + a[j] - a[i]
                s = i
    return lst[s:s+l]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM