Errors when defining the edges of an N x N matrix? Index: list index out of range

Asked

Viewed 82 times

-1

I created a function that takes as a parameter an Nxn matrix, and initially prints the top edge of the matrix, but I keep getting the error "Indexerror: list index out of range", and this prevents calling other functions.

def bordaSuperior(matriz): # Separa os números da borda superior
lin = 0
col = 0
for i in matriz: # Valores da Borda Superior
    for j in matriz:
        print(matriz[lin][col])
        col += 1
  • 1

    Your logic is wrong... You only increment the variable col, that is, if you have a 3x3 matrix you will try to access matriz[0][0] until matriz[0][8]. And as you can see there is no such element in the lists..

1 answer

3


The problem lies in the logic of your function. First of all, you do not restart the variable col after you’ve run the line. The consequence of this is that the variable will be incremented to a point where its value becomes larger than its line size, generating a IndexError.

Second, you travel in two loops for the matrix and not its lines. This means that col can have an index greater than the size of your line generating again a IndexError or the noose for may not scan all line values because the matrix size may be smaller than the line size. See below for the corrected code:

def bordaSuperior(matriz): 

    lin = 0

    for y in matriz:

        col = 0

        for x in y:

            print(matriz[lin][col])
            col += 1

        # lin += 1 se deseja imprimir todas as linhas e não só a primeira
  • Thanks, I managed to understand the mistake. Now it seems obvious, vlw!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.