Python: Replacing multiple for loops, multiple iterators

Viewed 260

I need your help. What is the most efficient way of substituting multiple nested for loops (over 5 nested loops into each other - 5 in the code example) if they all go through the same range (let's say from 1 to 10) and after the last for loop, at the bottom, i append every sum of the iterated items to the list. The code looks smth like this :

b=[]
for i in range(1, 11):
    for j in range(1, 11):
        for k in range(1, 11):
            for l in range(1, 11):
                for m in range(1, 11):
                    b.append(i+j+k+l+m)

It is obviously not memory-friendly and will take some time. As far as i know, itertools can not really help here either. So how could it be helped?

2 Answers

use itertools.product()

from itertools import product
b = [sum(item) for item in product(range(1, 11), repeat=5)]

You may want to make b generator, so that it is evaluated lazily

b = (sum(item) for item in product(range(1, 11), repeat=5))

I recommend using recursive programming. This happens when a function calls itself to do the same task with different parameters.

def someIteration(b, i, j, k, l, m):
    for i in range(1,11):
        b.append(i+j+k+l+m)
    if (Certain task done):
         return b
    else:
        someIteration(b, i, j, k, l, m)

I dont think this function will work directly, I recommend to do some research in recursive programming. It's a really interesting paradigm, mostly used in ai!

pros:

  • its very code efficient

cons:

  • when the stack is full, it will crash (this rarely happens, most of the time due to a bug.)
Related