这是一种使用默认参数的递归方法。下面的编号点是指代码中编号的cmets。
- (基础)深度为零。我们完成了,所以产生组合,
comb
- (inductive)深度至少为 1。对于范围内的每个
x,使用 x 作为嵌套范围的新起点委托给递归生成器,并将 x 附加到组合中,@ 987654325@.
def nested_range (depth = 0, start = 0, end = 1, comb = ()):
if depth == 0:
yield comb #1
else:
for x in range(start, end): #2
yield from nested_range(depth - 1, x, end, comb + (x,))
这是一个嵌套范围,深度为三 (3) 级 -
for p in nested_range (3, 0, 4):
print(p)
# (0, 0, 0)
# (0, 0, 1)
# (0, 0, 2)
# (0, 0, 3)
# (0, 1, 1)
# (0, 1, 2)
# (0, 1, 3)
# (0, 2, 2)
# (0, 2, 3)
# (0, 3, 3)
# (1, 1, 1)
# (1, 1, 2)
# (1, 1, 3)
# (1, 2, 2)
# (1, 2, 3)
# (1, 3, 3)
# (2, 2, 2)
# (2, 2, 3)
# (2, 3, 3)
# (3, 3, 3)
这个实现是一个总函数,当depth = 0时提供一个有效的结果-
for p in nested_range (0, 0, 4):
print(p)
# ()
为了更好地衡量,这里是嵌套范围的输出,深度为五 (5) 级 -
for p in nested_range (5, 0, 3):
print(p)
# (0, 0, 0, 0, 0)
# (0, 0, 0, 0, 1)
# (0, 0, 0, 0, 2)
# (0, 0, 0, 1, 1)
# (0, 0, 0, 1, 2)
# (0, 0, 0, 2, 2)
# (0, 0, 1, 1, 1)
# (0, 0, 1, 1, 2)
# (0, 0, 1, 2, 2)
# (0, 0, 2, 2, 2)
# (0, 1, 1, 1, 1)
# (0, 1, 1, 1, 2)
# (0, 1, 1, 2, 2)
# (0, 1, 2, 2, 2)
# (0, 2, 2, 2, 2)
# (1, 1, 1, 1, 1)
# (1, 1, 1, 1, 2)
# (1, 1, 1, 2, 2)
# (1, 1, 2, 2, 2)
# (1, 2, 2, 2, 2)
# (2, 2, 2, 2, 2)