Binh Thien
Binh Thien

Reputation: 395

why this python code results only last results

I'd like to calculate the matrix satisfying the condition:
result_x = 1 - initial_x;
result_y = initial_y and
results_z = initial_y.
However, my code results only the last one of each array. Could you please help me out?

import numpy as np
import math

def reverse_a_direction(matrix):
    reverse_a = []
    for (x, y, z) in matrix:
        reverse_a = 1 - x, y, z
    return reverse_a

a = np.array([[(0.1666666666666667, 0.8012144614989793, 0.7500000000000000), 
               (0.1666666666666667, 0.1987855385010207, 0.2500000000000000)], 
              [(0.6666666666666666, 0.3012144614989793, 0.7500000000000000), 
               (0.6666666666666666, 0.6987855385010207, 0.2500000000000000)]])

for i in range(0, len(a)):
    print(reverse_a_direction(a[i]))

Results of this code:

(0.8333333333333333, 0.1987855385010207, 0.25)
(0.3333333333333333, 0.6987855385010207, 0.25)

Expected results:

[(0.8333333333333333, 0.8012144614989793, 0.75), (0.8333333333333333, 0.1987855385010207, 0.25)],
[(0.3333333333333333, 0.3012144614989793, 0.75), (0.3333333333333333, 0.6987855385010207, 0.25)]

Upvotes: 1

Views: 78

Answers (3)

simonzack
simonzack

Reputation: 20938

Given your original array:

X = np.array([
    [
        [0.1666666666666667, 0.8012144614989793, 0.7500000000000000],
        [0.1666666666666667, 0.1987855385010207, 0.2500000000000000]
    ], 
    [
        [0.6666666666666666, 0.3012144614989793, 0.7500000000000000],
        [0.6666666666666666, 0.6987855385010207, 0.2500000000000000]
    ]
])

You can modify that one axis like this:

Y = np.array(X)
Y[:,:,0] = 1 - Y[:,:,0]

Upvotes: 0

S.N
S.N

Reputation: 5140

The reversing logic doesn't capture the results but is overwriting and hence you have the last result persisted in reverse_a[] variable.

change your assignment from

 reverse_a = 1 - x, y, z

to

 reverse_a.append((1 - x, y, z))

Upvotes: 0

w8eight
w8eight

Reputation: 623

You are overwriting reverse_a with each iteration. Right solution would be:

def reverse_a_direction(matrix):
    reverse_a = []
    for (x, y, z) in matrix:
        a = 1 - x, y, z
        reverse_a.append(a)
    return reverse_a

Upvotes: 5

Related Questions