给定一个正整数n
;print n-1
列表,长度递增,由Python中的连续整数组成。你知道吗
例如:对于n=4
,它应该打印列表(按顺序):
[[1], [2], [3], [4]], [[1, 2], [2, 3], [3, 4]], [[1, 2, 3], [2, 3, 4]]
我尝试了itertools
中的各种选项,但没有成功。你知道吗
编辑这里有一个失败的attepmt,使用combinations
:
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)]
这里的问题是(除了第一行中的空白列表),它在第三和第四行中打印更多的元素。你知道吗
我认为你只需要循环和切片:
输出:
提供替代解决方案:
我将使用
overlapping
函数。我想有些人把它叫做window
函数(?)。你知道吗像这样:
这将给你:
Peter Norvig has a lovely implementation of this.
用它做你想做的事情相当简单:
您也可以不用使用
collections
来实现这一点,但它不会这么短。你知道吗给你,我的两分钱。你知道吗
相关问题 更多 >
编程相关推荐