python matrices - list index out of range

Posted by user1888493 on Stack Overflow See other posts from Stack Overflow or by user1888493
Published on 2012-12-08T22:20:34Z Indexed on 2012/12/08 23:03 UTC
Read the original article Hit count: 175

Filed under:
|
|
|
|

I am writing a function, that takes a matrix as input, such as the one below. Then the it returns the matrix' inverse, where all the 1s are changed to 0s and all the 0s changed to 1s, while keeping the diagonal from top left to bottom right 0s.



An example input:

g1 = [[0, 1, 1, 0],
     [1, 0, 0, 1],
     [1, 0, 0, 1],
     [0, 1, 1, 0]]



the function should output this:

g1 = [[0, 0, 0, 1],
     [0, 0, 1, 0],
     [0, 1, 0, 0],
     [1, 0, 0, 0]]



When I run the program, it raises a list index out of range error. I'm sure this happens, because the loops I have set up are trying to access values that do not exist. But how do I allow an input of unknown row and column size? I only know how to do this with a single list, but a list of lists? Following you see the transforming function, but not the test function that calls it:

def inverse_graph(graph):
    # take in graph
    # change all zeros to ones and ones to zeros

    r, c = 0, 0 # row, column equal zero

    while (graph[r][c] == 0 or graph[r][c] == 1): # while the current row has a value.
        while (graph[r][c] == 0 or graph[r][c] == 1): # while the current column has a value
            if (graph[r][c] == 0):
                graph[r][c] = 1
            elif (graph[r][c] == 1):
                graph[r][c] = 0
            c+=1
        c=0
        r+=1

    c=0
    r=0

    # sets diagonal to zeros

    while (g1[r][c] == 0 or g1[r][c] == 1):
        g1[r][c]=0
        c+=1
        r+=1

    return graph

© Stack Overflow or respective owner

Related posts about python

Related posts about list