1

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 2

2

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))
Sign up to request clarification or add additional context in comments.

3 Comments

A cleaner way would be to use map: b = map(sum, product(range(1, 11), repeat=5))
@HarishRajagopal, this is a matter of personal preference and subject to a lot of discussions, incl here on SO (e.g. stackoverflow.com/q/2979290/4046632), at the same time Guido has clearly stated his preference for list comprehension .
Thanks a lot for the links! I found the discussions very interesting.
0

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.)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.