Reputation: 21
i have problem in which i have to test every element of an array with every other element in of the next array, and every element of the next array with every element of the next next array etc.... naturally i thought about nested loops but the problem is the number of arrays is given by the user so it would look like this :
for i in k:
for j in a[i]:
for k in a[i+1]:
for t in a[i+2]:
etc.......
so its a loop of loops how can i reduce this code???
Upvotes: 1
Views: 852
Reputation: 73
Recursion can be a good approach for this kind of problems:
def nested(a, i, end, elems = []):
if (i<end):
for j in a[i]:
elems.append(j)
nested(a, i+1, end, elems)
elems.pop(j)
else:
pass # here you can do the operation on the elements
for i in k:
nested(a, 0, len(a))
Upvotes: 1