Paradox
Paradox

Reputation: 4566

Converting nested for loops which constructs and prints lists to a resursive function

I'm trying to convert the following nested for loops which constructs and prints a list into a recursive function as it would greatly improve the runtime of it. However, I'm having difficulty with this. How could I go about converting it with so many layers of nested loops?

for v in range(-10, 11, 1):
     for w in range(-10, 11, 1):
            for x in range(-10, 11, 1):
                for y in range(-10, 11, 1):
                    for z in range(-10, 11, 1):
                        print([v, w, x, y, z])

Upvotes: 3

Views: 71

Answers (3)

Sebastien D
Sebastien D

Reputation: 4482

If I understood well, this could be a combination with replacement function done with itertools:

import itertools
import numpy as np

comb =  list(itertools.combinations_with_replacement(range(-10,11,1), 5))

for x in comb:
    print  np.asarray(x)

Upvotes: 1

Ajax1234
Ajax1234

Reputation: 71451

You can create default list in the function signature to store the elements you have currently accumulated, and once the length of the list equals the desired amount, yield the current list:

def combinations(count, args, current = []): 
    if len(current) == count:
       yield current
    else:
       for i in range(*args):
         yield from combinations(count, args, current + [i])

print(list(combinations(5, [-10, 11])))

Upvotes: 0

G_M
G_M

Reputation: 3372

As @mypetlion mentioned above, recursion in Python might not give you the performance boost you are looking for.

What about using itertools.product? I haven't benchmarked it compared to your original but it does seem to be implemented in C.

from itertools import product

for p in product(range(-10, 11), repeat=5):
    print(p)

Upvotes: 4

Related Questions