我试图弄清楚如何迭代任意数量的循环,其中每个循环取决于最近的外循环。以下代码是我想要执行的操作的示例:
def function(z):
n = int(log(z))
tupes = []
for i_1 in range(1, n):
for i_2 in range(1, i_1):
...
...
...
for i_n in range(1, i_{n - 1}):
if i_1*i_2*...*i_n > z:
tupes.append((i_1, i_2,..., i_n))
return tupes
Run Code Online (Sandbox Code Playgroud)
虽然我希望它适用于任何z> e**2,但它足以适用于zs 至e**100。我知道,如果我采用适当的 s 的笛卡尔积range,我最终会得到我想要的元组的超集,但我只想获得我想要的元组。
如果有人能帮助我解决这个问题,我将不胜感激。提前致谢。
您问题中的逻辑是递归实现的(请注意,这允许重复的元组):
import functools
def f(n, z, max_depth, factors=(), depth=0):
res = []
if depth == max_depth:
product = functools.reduce(lambda x, y: x*y, factors, 1)
if product > z:
res.append(factors)
else:
for i in range(1, n):
new_factors = factors + (i,)
res.extend(f(i, z, factors=new_factors, depth=depth+1, max_depth=max_depth))
return res
z = np.e ** 10
n = int(np.log(z))
print(f(n, z, max_depth=8))
Run Code Online (Sandbox Code Playgroud)
产量
[(8, 7, 6, 5, 4, 3, 2, 1),
(9, 7, 6, 5, 4, 3, 2, 1),
(9, 8, 6, 5, 4, 3, 2, 1),
(9, 8, 7, 5, 4, 3, 2, 1),
(9, 8, 7, 6, 4, 3, 2, 1),
(9, 8, 7, 6, 5, 3, 2, 1),
(9, 8, 7, 6, 5, 4, 2, 1),
(9, 8, 7, 6, 5, 4, 3, 1),
(9, 8, 7, 6, 5, 4, 3, 2)]
Run Code Online (Sandbox Code Playgroud)