【问题标题】:Longest distinct consecutive list in PythonPython中最长的不同连续列表
【发布时间】:2010-10-04 14:07:54
【问题描述】:

我有一个清单:

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

是否可以创建一个函数来显示最长的不同连续元素列表?

请教一下怎么做

在这种情况下,答案应该是:

13, 14, 15, 16, 17, 18

【问题讨论】:

  • 不清楚这些元素有什么特别之处或“0 或 1 变化”是什么意思。
  • “变化为 0 或 1”并不能真正解析成可以理解的东西。改写?
  • [2, 3, 5, 6, 6, 7, 10, 11, 13, 17, 14, 16, 15, 16, 18, 20, 21] 怎么样?
  • 请记住,计算机教师使用 S.O.太……

标签: python list iteration


【解决方案1】:

假设您的列表已排序:

>>> 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:固定最后一步;

【讨论】:

  • 我真的应该看看 itertools,不错 :D
【解决方案2】:

最简单的做法似乎是遍历列表一次,构建您可以找到的任何序列,然后打印最长的序列。

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)

【讨论】:

  • 这错过了序列中的最后一项是列表中的最后一项的边缘情况。例如,对于 [1,3,4,5,7,8,9,10],它返回 [3,4,5] 而不是 [7,8,9,10]
【解决方案3】:

可能还有一种更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]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-16
    • 1970-01-01
    • 1970-01-01
    • 2016-07-17
    • 2011-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多