[Solved] Numpy arrays in a for loop [closed]


Solution:

val_A = []
val_B = []
val_A.append(A1)
val_B.append(B1)

for i in range(5):
    val_A.append(val_B[-1] * Z2)
    val_B.append(val_A[-1] * Z1)

Demo:
(On a simple test case, to show that it works)

# Manual
Z1 = 2
Z2 = 3
A1 = 5
B1 = 7
A2 = B1*Z2
B2 = A2*Z1
A3 = B2*Z2
B3 = A3*Z1

print([A1, A2, A3], [B1, B2, B3])

# With for loop

val_A = []
val_B = []
val_A.append(A1)
val_B.append(B1)

for i in range(2):
    val_A.append(val_B[-1] * Z2)
    val_B.append(val_A[-1] * Z1)

print(val_A, val_B)

Yields:

[5, 21, 126] [7, 42, 252]
[5, 21, 126] [7, 42, 252]

Explanation:

The OP code mixes up Z1 and Z2 (the B’s should be multiplied by Z2) and also uses the wrong indices for choosing items from the lists (this code avoids that by using ‘-1’ to always take the last item from each list).

3

solved Numpy arrays in a for loop [closed]