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?

rdas
  • 20,604
  • 6
  • 33
  • 46
Alan
  • 9
  • 3

2 Answers2

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))
buran
  • 13,682
  • 10
  • 36
  • 61
  • 1
    A cleaner way would be to use `map`: `b = map(sum, product(range(1, 11), repeat=5))` – Harish Rajagopal Mar 23 '21 at 09:09
  • 1
    @HarishRajagopal, this is a matter of personal preference and subject to a lot of discussions, incl here on SO (e.g. https://stackoverflow.com/q/2979290/4046632), at the same time Guido has clearly [stated his preference for list comprehension](https://www.artima.com/weblogs/viewpost.jsp?thread=98196) . – buran Mar 23 '21 at 09:20
  • Thanks a lot for the links! I found the discussions very interesting. – Harish Rajagopal Mar 24 '21 at 10:08
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.)