【问题标题】:How to find the longest consecutive chain of numbers in an array如何找到数组中最长的连续数字链
【发布时间】:2017-06-06 14:11:08
【问题描述】:

例如,我们有 [0, 1, 3, 5, 7, 8, 9, 10, 12, 13]

结果必须是7, 8, 9, 10,因为它们彼此相邻,按索引排列并且是连续整数,而且这条链比0, 1长。

英语不是我的第一语言,如果写作有点晦涩,请见谅。

【问题讨论】:

  • 这里有一些代码高尔夫或家庭作业
  • 这不是作业,我正在尝试使用这种方法解决一个问题,但似乎无法弄清楚
  • 使用for循环:如果n

标签: python arrays


【解决方案1】:

使用itertools.groupby根据与递增计数的恒定差异将项目分组为子序列(由itertools.count对象提供),然后使用键上的内置max获取最长的子序列 参数len:

from itertools import groupby, count

lst = [0, 1, 3, 5, 7, 8, 9, 10, 12, 13]
c = count()
val = max((list(g) for _, g in groupby(lst, lambda x: x-next(c))), key=len)
print(val)
# [7, 8, 9, 10]

您可以在结果中包含组键(隐藏为 _)以进一步了解其工作原理。

【讨论】:

  • 这真是太棒了。
【解决方案2】:

使用numpy 模块的替代解决方案:

import numpy as np

nums = np.array([0, 1, 3, 5, 7, 8, 9, 10, 12, 13])
longest_seq = max(np.split(nums, np.where(np.diff(nums) != 1)[0]+1), key=len).tolist()    
print(longest_seq)

输出:

[7, 8, 9, 10]

  • np.where(np.diff(nums) != 1)[0]+1 - 获取应该拆分数组的元素的索引(如果两个连续数字之间的差不等于1,例如35

  • np.split(...) - 将数组拆分为子数组

https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.diff.html#numpy.diff https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.split.html

【讨论】:

    【解决方案3】:

    代码

    使用itertools.groupby(类似于@Moses Koledoye 的回答):

    groups = [[y[1] for y in g] for k, g in itertools.groupby(enumerate(iterable), key=lambda x: x[0]-x[1])]
    groups
    # [[0, 1], [3], [5], [7, 8, 9, 10], [12, 13]]
    
    max(groups, key=len)
    # [7, 8, 9, 10]
    

    另类

    考虑第三方工具more_itertools.consecutive_groups

    import more_itertools as mit
    
    
    iterable = [0, 1, 3, 5, 7, 8, 9, 10, 12, 13]
    max((list(g) for g in mit.consecutive_groups(iterable)), key=len)
    # [7, 8, 9, 10]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-02
      • 2019-02-24
      • 2013-05-19
      • 2015-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多