Skip to main content
 首页 » 编程设计

python之识别排序列表中不同的连续倍数

2024年11月01日11xiaohuochai

我有一个排序列表,我想在该列表中识别连续的多个数字。该列表可以包含不同顺序的连续倍数,这使得它变得更加困难。

一些测试用例:

[1,3,4,5] -> [[1], [3,4,5]] 
[1,3,5,6,7] -> [[1], [3], [5,6,7]] 
# consecutive multiples of 1 and 2 (or n) 
[1,2,3,7,9,11] -> [[1,2,3], [7,9,11] 
[1,2,3,7,10,12,14,25] -> [[1,2,3], [7], [10,12,14], [25]] 
# overlapping consecutives !!! 
[1,2,3,4,6,8,10] -> [[1,2,3,4], [6,8,10] 

现在,我不知道自己在做什么。我所做的是按数字之间的距离成对分组,这是一个好的开始,但后来我遇到了很多问题,无法确定每对中的哪个元素去哪里,即

 # initial list     
 [1,3,4,5] 
 # pairs of same distance 
 [[1,3], [[3,4], [4,5]] 
 # algo to get the final result ? 
 [[1], [3,4,5]] 

非常感谢任何帮助。

编辑:也许提及我想要它的目的会使它更清楚。

我想转换这样的东西:

[1,5,10,11,12,13,14,15,17,20,22,24,26,28,30] 

进入

1, 5, 10 to 15 by 1, 17, 20 to 30 by 2 

请您参考如下方法:

这是包含@Bakuriu 优化的版本:

MINIMAL_MATCH = 3 
 
def find_some_sort_of_weird_consecutiveness(data): 
    """ 
    >>> find_some_sort_of_weird_consecutiveness([1,3,4,5]) 
    [[1], [3, 4, 5]] 
    >>> find_some_sort_of_weird_consecutiveness([1,3,5,6,7]) 
    [[1, 3, 5], [6], [7]] 
    >>> find_some_sort_of_weird_consecutiveness([1,2,3,7,9,11]) 
    [[1, 2, 3], [7, 9, 11]] 
    >>> find_some_sort_of_weird_consecutiveness([1,2,3,7,10,12,14,25]) 
    [[1, 2, 3], [7], [10, 12, 14], [25]] 
    >>> find_some_sort_of_weird_consecutiveness([1,2,3,4,6,8,10]) 
    [[1, 2, 3, 4], [6, 8, 10]] 
    >>> find_some_sort_of_weird_consecutiveness([1,5,10,11,12,13,14,15,17,20,22,24,26,28,30]) 
    [[1], [5], [10, 11, 12, 13, 14, 15], [17], [20, 22, 24, 26, 28, 30]] 
    """ 
    def pair_iter(series): 
        from itertools import tee 
        _first, _next = tee(series) 
        next(_next, None) 
        for i, (f, n) in enumerate(zip(_first, _next), start=MINIMAL_MATCH - 1): 
            yield i, f, n 
 
    result = [] 
    while len(data) >= MINIMAL_MATCH: 
        test = data[1] - data[0] 
        if (data[2] - data[1]) == test: 
            for i, f, n in pair_iter(data): 
                if (n - f) != test: 
                    i -= 1 
                    break 
        else: 
            i = 1 
        data, match = data[i:], data[:i] 
        result.append(match) 
    for d in data: 
        result.append([d]) 
    return result 
 
if __name__ == '__main__': 
    from doctest import testmod 
    testmod() 

它处理您当前所有的测试用例。如果有新的失败测试用例,请给我。

正如下面评论中提到的,我假设最短序列现在是三个元素,因为两个元素的序列是微不足道的。

参见 http://docs.python.org/2/library/itertools.html对成对迭代器的解释。