Array scheduling in Python

1

I have problems trying to stagger an array 5x5 . First I caused a null line to go to the last line of the array (it worked), then I tried to make a line that had the highest index stay below the one with a smaller index, but on the line:

if pivos_indices[i] > pivos_indices[linha_aux] and linha_aux < 5 and i < 5:

From the code, the compiler warns that the list index is out of range, but I do not know why (that's the problem). Here is the code:

import numpy as np

def buscar_pivo(L):
    if (np.nonzero(L)[0]).size == 0:
        return -1
    else:
        return np.nonzero(L)[1][0]

def encontrar_pivos_indices(mat):
    pivos = []
    for i in range(5):
        pivos.append(buscar_pivo(np.array(mat[i])))
    return pivos

mat = np.matrix([[0,5,2,7,8],[8,10,4,14,16],[0,0,0,0,0],[2,6,10,16,22],[3,5,8,9,15]]).astype(float)
print("Matriz original:\n",mat,"\n")

pivos_indices = encontrar_pivos_indices(mat)

linha_aux = 0
for i in range(5):
    linha_aux = linha_aux + 1
    if pivos_indices[i] == -1 and linha_aux < 5 and i < 5:
        m = mat.tolist()
        (m[i],m[linha_aux]) = (m[linha_aux],m[i])
        mat = np.matrix(m)
        pivos_indices = encontrar_pivos_indices(mat)

print(mat,"\n")

linha_aux = 0
for i in range(5): 
    linha_aux = linha_aux + 1
    if pivos_indices[i] > pivos_indices[linha_aux] and linha_aux < 5 and i < 5:
        m = mat.tolist()
        (m[i],m[linha_aux]) = (m[linha_aux],m[i])
        mat = np.matrix(m)
        pivos_indices = encontrar_pivos_indices(mat)

print(mat)
    
asked by anonymous 14.10.2017 / 15:27

1 answer

1

There are five possible indexes in your array, ranging from 0 to 4 . In the line

for i in range(5):

You run five iterations, making the value of linha_aux vary from 1 to 5 . That way, in the last iteration you will try to access an index that does not exist.

To solve the problem, simply move the line that increments the linha_aux counter to the iteration end :

for i in range(5): 
    if pivos_indices[i] > pivos_indices[linha_aux] and linha_aux < 5 and i < 5:
        m = mat.tolist()
        (m[i],m[linha_aux]) = (m[linha_aux],m[i])
        mat = np.matrix(m)
        pivos_indices = encontrar_pivos_indices(mat)
    linha_aux = linha_aux + 1
    
23.10.2017 / 01:46