任意数量的嵌套循环依赖于Python中的前一个循环

时间:2016-02-26 19:00:40

标签: python loops

我试图弄清楚如何迭代任意数量的循环,其中每个循环依赖于最近的外循环。以下代码是我想要做的一个例子:

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

虽然我希望这适用于任何z> e**2z一直到e**100就足够了。我知道,如果我采用适当的range s的笛卡尔积,我最终会得到我想要的元组的超集,但我只想获得我所寻求的元组。

如果有人可以帮助我,我会非常感激。提前谢谢。

3 个答案:

答案 0 :(得分:2)

组合可以按升序列出;实际上,这是itertools.combinations的默认行为。

代码:

for i1 in range(1,6):
    for i2 in range(1,i1):
        for i3 in range(1,i2):
            print (i3, i2, i1)

# (1, 2, 3)
# (1, 2, 4)
# ...
# (3, 4, 5)

等同于代码:

from itertools import combinations

for combination in combinations(range(1,6), 3):
    print combination

# (1, 2, 3)
# (1, 2, 4)
# ...
# (3, 4, 5)

使用组合代替笛卡尔积,可以将样本空间剔除到您想要的范围。

答案 1 :(得分:1)

正如zondo建议的那样,您需要使用函数和递归来完成此任务。以下内容应该有效:

def recurse(tuplesList, potentialTupleAsList, rangeEnd, z):
    # No range to iterate over, check if tuple sum is large enough
    if rangeEnd = 1 and sum(potentialTupleAsList) > z:
        tuplesList.append(tuple(potentialTupeAsList))
        return
    for i in range(1, rangeEnd):
        potentialTupleAsList.append(i)
        recurse(tuplesList, potentialTupleAsList, rangeEnd - 1, z)
        # Need to remove item you used to make room for new value
        potentialTupleAsList.pop(-1)

然后你可以这样称呼它来获得结果:

l = []
recurse(l, [], int(log(z)), z)
print l

答案 2 :(得分:1)

您的问题中的逻辑以递归方式实现(请注意,这允许重复的元组):

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))

产量

[(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)]