Skip to content Skip to sidebar Skip to footer

Algorithm For Arbitrary Number Of Nested For Loops

I am trying to figure out an algorithm to generalise my code for an arbitrary integer value of a parameter that in my code controls the number of nested for loops. My code schemat

Solution 1:

As pointed out, this will blowup very quickly. However you can use cartesian product iterator:

import itertools
import numpy as np

# Create a list with ranges:
rngs=np.array([p,q,..,z])

#Initialize X empty
X = np.empty((rngs.prod(), A.shape[0]))

#Cycle over all cartesian productsfor i,t inenumerate(itertools.product(*[range(i) for i in rngs])):
    X[i,:] = sum([A[i,:] * t[i] for i inrange(len(t))])

Test data:

A = np.random.randint(10, size=(10, 10))
A
array([[8, 5, 0, 2, 0, 4, 5, 5, 0, 9],
       [7, 0, 5, 9, 9, 4, 8, 2, 6, 8],
       [4, 3, 8, 5, 2, 5, 4, 8, 6, 1],
       [0, 5, 6, 5, 5, 0, 8, 5, 4, 9],
       [3, 3, 2, 6, 6, 9, 7, 7, 3, 3],
       [4, 0, 7, 2, 3, 2, 2, 4, 1, 2],
       [6, 2, 5, 9, 9, 9, 4, 7, 7, 3],
       [6, 3, 4, 9, 0, 3, 8, 1, 6, 8],
       [6, 5, 6, 0, 8, 7, 9, 0, 7, 4],
       [2, 1, 4, 1, 3, 8, 3, 3, 2, 9]])

rngs = np.random.randint(1, 5, size=10)
rngs
array([4, 2, 1, 2, 2, 3, 4, 4, 2, 4])

X = np.empty((rngs.prod(), A.shape[0]))

for i,t in enumerate(itertools.product(*[range(i) for i in rngs])):
    X[i,:] = sum([A[i,:] * t[i] for i in range(len(t))])

X
array([[  0.,   0.,   0., ...,   0.,   0.,   0.],
       [  2.,   1.,   4., ...,   3.,   2.,   9.],
       [  4.,   2.,   8., ...,   6.,   4.,  18.],
       ...,
       [ 86.,  44.,  64., ...,  64.,  63.,  97.],
       [ 88.,  45.,  68., ...,  67.,  65., 106.],
       [ 90.,  46.,  72., ...,  70.,  67., 115.]])

Solution 2:

First up: Are you sure you want to do this? The number of actual statements executed is going to get large very quickly as the number of loops increases, your code is going to be slow with anything other than a very small number of loops, possibly so slow as to make its use impractical. I'd think about whether you really need all those loops.

Leaving that aside, I'd do this recursively:

defnextloop(counter, coefficients, vectors):
    counter = counter - 1if counter == 0:
        result = 0for i inrange(len(vectors)):
            result += coefficients[i] * vectors[i]
        return result
    else:
        return nextloop(counter, coefficients, vectors)

finalresult = nextloop(5, coeffs, vecs) # Adjust initial call appropriately

This isn't exactly right because I'm not quite clear on what your algorithm does on each loop, but you can amend it as needed.

Post a Comment for "Algorithm For Arbitrary Number Of Nested For Loops"