生成一系列连续整数递增长度的列表

时间:2019-05-06 15:29:23

标签: python python-2.7

给出一个正整数n;打印n-1列表,这些列表的长度不断增加,并且由Python中的连续整数组成。

示例:对于n=4,它应按顺序打印列表:

[[1], [2], [3], [4]], [[1, 2], [2, 3], [3, 4]], [[1, 2, 3], [2, 3, 4]]

我尝试了itertools中的各种选项,但是没有运气。

EDIT 这是一个combinations失败的attepmt:

n = 4
from itertools import product, permutations, tee, combinations
for i in range(n):
    print list(combinations(range(1, n+1), r = i))

它打印

[()]
[(1,), (2,), (3,), (4,)]
[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
[(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]

这里的问题是(第一行的空白列表除外),它在第三行和第四行打印更多的元素。

2 个答案:

答案 0 :(得分:2)

我认为您只需要循环和切片:

def increasingLengths(n):
    ret = []
    sample = [i + 1 for i in range(n)]
    for i in range(1, n):
        aList = []
        maxItems = n - i + 1
        for j in range(maxItems):
            aList.append(sample[j:j + i])
        ret.append(aList)
    return ret

print(increasingLengths(4))

输出:

[[[1], [2], [3], [4]], [[1, 2], [2, 3], [3, 4]], [[1, 2, 3], [2, 3, 4]]]

答案 1 :(得分:1)

要提供替代解决方案:

我将使用overlapping函数。我认为有人称它为window函数(?)。

类似这样的东西:

from collections import deque

def overlapping(seq, n):
    result = deque(seq[:n], maxlen=n)
    yield tuple(result)
    for x in seq[n:]:
        result.append(x)
        yield tuple(result)

哪个会给你:

>>> list(overlapping('abcdefg', 3))
[('a', 'b', 'c'), ('b', 'c', 'd'), ('c', 'd', 'e'), ('d', 'e', 'f'), ('e', 'f', 'g')]

Peter Norvig has a lovely implementation of this.

使用您想要的东西很简单:

def increasing_lengths(n):
    seq = list(range(1, n + 1))
    for i in range(1, n):
        yield list(overlapping(seq, i))

>>> list(increasing_lengths(4))
[[(1,), (2,), (3,), (4,)], [(1, 2), (2, 3), (3, 4)], [(1, 2, 3), (2, 3, 4)]]

您也可以不使用collections来执行此操作,但是它不会那么短。

去了,我的两分钱。