5

I am trying to find the formula to count every iteration of this double for loop (in python for instance):

for i in range(5):
   for j in range(5):
       count = MYSTERIOUS_FORMULA
       print count

Here the final value of count should be 25.

I tried count=(i+1)*j but it produce 0,1,2,3,4,0,2,4 etc.

MSeifert
  • 145,886
  • 38
  • 333
  • 352
SdFRO0QS78
  • 91
  • 1
  • 2
  • 5
  • 1
    You need to initialise `count` outside the inner loop, you're resetting it every time you iterate in the outer loop – EdChum Apr 27 '17 at 14:33

4 Answers4

10

The mysterious formula is quite simple:

{count} = {index of current loop} + {size of current loop}*{count of parent loop}

As an example, consider a single loop:

x = 5

for i in range(x):
    count = i

To be explicit, count = i + x*0 but the second term is irrelevant because there is no parent loop. An example of two loops might be more illuminating:

x = 5
y = 6

for i in range(x):
    for j in range(y):
        count = j + y*(i)

Notice that I put i in parentheses to emphasize that it is the {count of parent loop}. This formula can be easily expanded to a third loop:

x = 5
y = 6
z = 7

for i in range(x):
    for j in range(y):
        for k in range(z):
            count = k + z*(j + y*(i))

and so on...

Splic
  • 298
  • 3
  • 8
7

The Double-for-loop (a.k.a. Nested loops).

# Set count to 0 before loop starts
count = 0

for i in range(5):
    for j in range(5):
        # solved mysterious formula (short hand 'count = count + 1')
        count += 1
# displaying count after loop
print(count)

Expanding on the formula count = count + 1, this sets count to be equal itself + 1:

count = count + 1
foxyblue
  • 2,859
  • 2
  • 21
  • 29
2

If you want to compute the number in each iteration:

for i in range(5):
   for j in range(5):
       count = 5*i+j+1
       print count
Yaakov Belch
  • 4,692
  • 33
  • 39
1

The easiest way would be to use itertools.product and enumerate:

from itertools import product

for idx, (i, j) in enumerate(product(range(5), range(5)), 1):
    print(idx, i, j)

which prints:

1 0 0
2 0 1
3 0 2
4 0 3
5 0 4
[...]
24 4 3
25 4 4
MSeifert
  • 145,886
  • 38
  • 333
  • 352