Iteration counter for double loops

I am trying to find a formula for counting each iteration of this double loop for(e.g. in python):

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

Here the final count should be 25.

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

+4
source share
4 answers

Double-for-loop (aka 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 by the formula count = count + 1, this establishes itself countas equal+ 1:

count = count + 1
+3
source

If you want to calculate the number at each iteration:

for i in range(5):
   for j in range(5):
       count = 5*i+j+1
       print count
+2
source

- itertools.product enumerate:

from itertools import product

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

:

1 0 0
2 0 1
3 0 2
4 0 3
5 0 4
[...]
24 4 3
25 4 4
0

:

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

:

x = 5

for i in range(x):
    count = i

To be explicit, count = i + x*0but the second term does not matter, because there is no parent cycle. An example of two cycles can be more illuminated:

x = 5
y = 6

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

Note that I put iin parentheses to emphasize what it is {count of parent loop}. This formula can be easily extended to the third cycle:

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

etc.

0
source

Source: https://habr.com/ru/post/1675807/


All Articles