1

My question is quite similar to this one here: Function with varying number of For Loops (python)

However, what I really want is for example:

def loop_rec(n):
    for i in range(n):
        for j in range(n):
            for k in range(n):
                #... n loops
                    #Do something with i, j and k 
                    #Such as i+j+k

The example in the link does not allow the index x to vary.

Something like the answer suggested in that question but to use the indices instead of just x.

def loop_rec(y, n):
    if n >= 1:
        for x in range(y): # Not just x
            loop_rec(y, n - 1)
    else:
       whatever()

Thanks

Community
  • 1
  • 1
Jonathan
  • 13
  • 3

1 Answers1

2

For problems where you have to deal with multiple nested loops, python standard library provides a convenient tool called itertools.product

In your particular case, all you have to do is to wrap the range with itertools.product, and specify how many nested loops via the repeat parameter. itertools.product, necessarily performs Cartesian product.

def loop_rec(y, n):
    from itertools import product
    for elems in product(range(y),repeat=n):
        # sum(args)
        # x,y,z ....(n) terms = elems 
        # index elems as elems[0], elems[1], ....

based on your requirement, you might want to use the entire tuple of each Cartesian product, or might want to index the tuple individually, or if you know the loop depth, you can assign it to the variables.

Thanks, but what if I wanted to change the range for each loop, ie. i in range(n), j in range(n-1), k in range(n-2)

Assuming, you want to vary the range from m to n i.e. range(n), range(n-1), range(n-2), .... range(m). you can rewrite the product as

product(*map(range, range(m,n)))

.

Abhijit
  • 62,056
  • 18
  • 131
  • 204
  • Thanks, but what if I wanted to change the range for each loop, ie. i in range(n), j in range(n-1), k in range(n-2)... etc – Jonathan Sep 24 '14 at 17:00