Home > Back-end >  How to create variable dual for loops?
How to create variable dual for loops?

Time:11-27

I want to create a function that behaves the same way as the for loops down there, dependant on the variable n:

function(n, max_anz, max_size_ , step)

n = 1

z = 0
for a1 in range(max_anz   1):
    for x1 in range(0, max_size, step):
        
        print([a1, x1])
        z  = 1
print(z)

n = 2

z = 0
for a1 in range(max_anz   1):
    for x1 in range(0, max_size, step):
        
        for a2 in range(max_anz   1):
            for x2 in range(0, max_size, step):
                
                print([a1, x1, a2, x2])
                z = z 1
print(z)

n = 3

z = 0
for a1 in range(max_anz   1):
    for x1 in range(0, max_size, step):
        
        for a2 in range(max_anz   1):
            for x2 in range(0, max_size, step):
                
                for a3 in range(max_anz   1):
                    for x3 in range(0, max_size, step):
                
                        print([a1, x1, a2, x2, a3, x3])
                        z = z 1

print(z)

CodePudding user response:

Using itertools.product with its 'repeat' argument.

import itertools as it

def function(n, max_anz, max_size, step):
    lst = [list(e) for e in it.product(range(max_anz 1), range(0, max_size, step), repeat = n)]
    print(*lst, sep='\n')
    print(len(lst))

Or with a generator to prevent building the full list:

def function(n, max_anz, max_size, step):
    g = it.product(range(max_anz 1), range(0, max_size, step), repeat = n)
    
    for i, e in enumerate(g):
        print(list(e))
    print(i 1)

which could be shortened:

def function(n, max_anz, max_size, step):
    for i, e in enumerate(it.product(range(max_anz 1), range(0, max_size, step), repeat = n)):
        print(list(e))
    print(i 1)

CodePudding user response:

You could do what you want using recursion, with a function that calls itself with n-1 (if n is greater than one) and passes in some partial results to build on.

The snippet below demonstrates this approach on a simpler problem with only a single for loop at each level of n.

def make_list(n, limit, context=None):
    z = 0
    for val in range(limit):
        new_list = [] if context is None \
            else context.copy()
        new_list.append(val)
        if n > 1:
            z  = make_list(n-1, limit, context=new_list)
        else:
            print(new_list)
            z  = 1
    return z

make_list(2, 3)
# [0, 0]
# [0, 1]
# [0, 2]
# [1, 0]
# [1, 1]
# [1, 2]
# [2, 0]
# [2, 1]
# [2, 2]
# Out[10]: 9
  • Related