动态生成灵活数量的嵌套for循环 [英] Dynamically generating a flexible number of nested for loops

查看:403
本文介绍了动态生成灵活数量的嵌套for循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以根据输入的长度来增加/减少嵌套的for循环数?

Is it possible to add/reduce number of nested for loops in a function based on the length of input?

例如:
基于a某些长度为3的输入,我可能需要使用1个嵌套的for循环(for循环在另一个for循环内)。与此类似,

For example: Based on a certain input of length 3, I may need to use 1 nested for loop (for loop inside another for loop). Similar to this,

for i in range(0, len(input)+1):
    for j in range(i+1, len(input)+1):

但是,当输入长度为4时,如果可以在已经存在的嵌套for循环中引入其他for循环,则可以实现我的结果,这意味着

However, when the input length is 4, I could have achieved my result if I could introduce additional for loop inside the already existing nested for loop, which means,

for i in range(0, len(input)+1):
    for j in range(i+1, len(input)+1):
        for k in range(j+1, len(input)+1):`

同样,如果输入长度为5,那么我想引入另一个for循环,

Similarly, if the input length is 5, then I would like to introduce another for loop,

for i in range(0, len(input)+1):
    for j in range(i+1, len(input)+1):
        for k in range(j+1, len(input)+1):
            for l in range(k+1, len(input)+1):`

模式是,将有n-1个for循环fo

The pattern is, there will be n-1 number of for loops for an input of length n.

是否可以在Python中创建这样的函数?

Is it possible create such a function in Python?

推荐答案

从此文章代码用C编写并急速转换为python可以为您提供:

From this article the code written in C and hastily translated to python gives you this:


如果我们看一下嵌套循环的工作方式,我们会发现最里面的
循环大部分时间都起作用,只有当我们
的内部循环中的值用尽时,才需要上循环。

If we look at how the nested loops work, we see that the inner most loop works most of time and the upper loops are needed only when we run out of values in the inner loops.

将其转换为一个动态嵌套循环,我们可以在数组中表示
个不同的循环变量。为了简单起见,假设
的变量上限是一个常量,如上面的
示例中所示。

To convert this into a dynamic nested loop we can represent the different loop variables in an array. For simplicity lets assume that the upper bound of these variables are a constant as in the above example.

要实现动态嵌套循环,我们需要增加最里面的
循环变量,直到我们用完值。只有到那时,我们才需要看看
改变了上层循环变量。

To implement a dynamic nested loop we need to increment the inner most loop variable until we run out values. Only then do we need to look at changing the upper level loop variables.

虽然此代码段生成了组合代码,但它

While this snippet is generating combinatorics, it is maybe possible to imagine re-using it for a different purpose.

如评论中所述,这可能不是一个好的设计选择。

必须使用一种更好的(更Python化的)方式使用生成器,或者使用异步方法,而不是增加间接级别。

As mentioned in the comments, it may not be a good design choice.
There has to be a better (more pythonic) way using generators, or maybe async, than increasing the level of indirection.

当然,还有递归,但是

MAXROWS = 4      #    contains the number of levels
MAXVALUES = 2    #    contains the maximum combination for a given nested variables.

display = ['1', '2', '3', '4', '5', '6', '7', '8', '9']

arrs = [0] * MAXROWS   # represent the different variables in the for loops                      
status = False

while not status: 

    total = 0
    # calculate total for exit condition
    for r in range(MAXROWS):
        total += arrs[r]
        # test for exit condition
    if total == (MAXVALUES - 1) * MAXROWS:
        status = True

    # printing
    for r in range(MAXROWS):
        print(display[arrs[r]], end=' ')  # print(arrs[r])
    print()

    # increment loop variables
    change = True
    r = MAXROWS-1    # start from innermost loop

    while change and r >= 0:
    # increment the innermost variable and check if spill overs
        if (arrs[r] + 1) > MAXVALUES-1:    
            arrs[r] += 1
            arrs[r] = 0     #  // reintialize loop variable
            # Change the upper variable by one
            # We need to increment the immediate upper level loop by one
            change = True   
        else:
            arrs[r] += 1
            change = False   # Stop as there the upper levels of the loop are unaffected

            # We can perform any inner loop calculation here arrs[r]

        r -= 1  #  move to upper level of the loop



输出:



output:

1 1 1 1 
1 1 1 2 
1 1 2 1 
1 1 2 2 
1 2 1 1 
1 2 1 2 
1 2 2 1 
1 2 2 2 
2 1 1 1 
2 1 1 2 
2 1 2 1 
2 1 2 2 
2 2 1 1 
2 2 1 2 
2 2 2 1 
2 2 2 2

这篇关于动态生成灵活数量的嵌套for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆