Variable used in multiple for-loop

Tweet


Some people do not know how the followings.

Imagine the following program. Two for-loops sequentially run. Suppose that these two for-loops cannot be merged for a certain reason. The first for-loop is processed, and after that, the second for-loop is processed.

for-loop:
    Take 1 element from array A
    Some calculation is done to that element
for-loop:
    Some calculation is done to the result of the previously processed value
    Save the result to array B

Some people implement as follows.

import numpy as np
first=np.zeros(10)
final=np.zeros(10)
for i in range(10):
    a=first[i]
    a=a+i
    middle=a
for i in range(10):
    a=middle
    a=a*2
    final[i]=a
print(final)

The result is shown below, which is wrong.

[18. 18. 18. 18. 18. 18. 18. 18. 18. 18.]

This is because you didn't imagine what number is in each variable.
This is because you didn't understand the procedure of the source code.

Let's solve this problem. Here is an example. Variable is a kind of a box. Imagine you put a numerical value into the box. You already heard this explanation in the early stage of studying the programming. You may think "I know this story". I can't understand why you mistaked even if you know that variables are kind of boxes. Why did you mistake? Have you never put anything in a box before?

First, the above code put the value 0 into the box "middle".

Let's go on to the next loop. The above code put the value 1 into the box "middle". The value is override. The value 0 disappears, and the box has the value 1. Only 1 value can be put into one box. The size of the box is just the same size of the value to be put in.

The value 9 is put into the box "middle" at the final loop.

Bring a value outside from the box "middle" at the beginning of the next for-loop. The value 18 will be put into the box "final[0]".

The next loop put 18 into the box "final[1]".

The value 18 is put into the box "final[9]" at the final loop.

How to solve this problem? Easy. Prepare 10 boxes. Why couldn't you solve the problem?

The correct code is as follows.

import numpy as np
first=np.zeros(10)
middle=np.zeros(10)
final=np.zeros(10)
for i in range(10):
    a=first[i]
    a=a+i
    middle[i]=a
for i in range(10):
    a=middle[i]
    a=a*2
    final[i]=a
print(final)

The correct result is as follows.

[ 0. 2. 4. 6. 8. 10. 12. 14. 16. 18.]

First, the value 0 is put into the box "middle[0]". Next loop put 1 into the box "middle[1]". Final loop put 9 into the box "middle[9]".

The first loop of the next for-loop brings the value from the box "middle[0]", and put the value 0 into the box "final[0]". Next loop doubles the value of the box "middle[1]" and puts it into the box "final[1]". Continue this process until the final loop puts 18 into the box "final[9]".

Elementary. You should have solved this problem without reading this webpage.


Back