Line change in array

3

Hello. I was programming in python and wanted to do the line switching (between the second and third line) of an array using the following code. But I wanted to know why the variable auxLinha changes value when I modify b[inicio]

def trocaLinhaB(b,inicio,final):
    listaAux = b[inicio]
    b[inicio] = b[final]
    b[final] = listaAux

The original matrix

0 2 3
0 -3 1
2 1 5

But the result was

[[ 0.  2.  3.]
 [ 0. -3.  1.]
 [ 0. -3.  1.]]

And I expected the

[[ 0.  2.  3.]
 [ 2.  1.  5.]
 [ 0. -3.  1.]]
    
asked by anonymous 01.12.2016 / 04:43

1 answer

3

I believe you are using the numpy library, so the variable listaAux stores only one view of the array and not the data (and therefore "changes" the value).

When you change the array, you also change the display.

One possible solution to this problem is to store a copy of the data in the listaAux variable before making the substitution.

The function code looks like this:

def trocaLinhaB(b,inicio,final):
    listaAux = b[inicio].copy()  # <= aqui: cria uma cópia
    b[inicio] = b[final]
    b[final] = listaAux
    
01.12.2016 / 05:39