Search code examples
pythonlistmatrixrangeout

python matrices - list index out of range


Hey I am writing a function that takes a matrix input such as the one below and returns its 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 throws a "list index out of range" error. I'm sure this is 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? Here is the function, not including 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

Solution

  • This doesn't directly answer your question, but I want to point out that in Python you can often reduce and sometimes eliminate the need to use indexing by using a
        for <element> in <container>:
    statement. By use it along with the built-in enumerate() function, it's possible to get both the index and the corresponding element
        for <index>,<element> in enumerate(<container>):

    Applying them to your problem would allow something like this:

    g1 = [[0, 1, 1, 0],
          [1, 0, 0, 1],
          [1, 0, 0, 1],
          [0, 1, 1, 0]]
    
    def inverse_graph(graph):
        """ invert zeroes and ones in a square graph
            but force diagonal elements to be zero
        """
        for i,row in enumerate(graph):
            for j,cell in enumerate(row):
                row[j] = 0 if cell or i == j else 1
        return graph
    
    print(g1)
    print(inverse_graph(g1))
    

    Output:

    [[0, 1, 1, 0], [1, 0, 0, 1], [1, 0, 0, 1], [0, 1, 1, 0]]
    [[0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0], [1, 0, 0, 0]]
    

    Which is simpler and clearly works. Another point is that since you're applying the function to a mutable (changeable) container, a list-of-lists, there's really no need to return the container because it is being changed in-place. It's not wrong to do so because it can make using the function easier, but it's something you may not have realized.

    You could shorten the function a little bit more and eliminate indexing altogether by using something called a list comprehension:

    def inverse_graph(graph):
        return [[0 if cell or i == j else 1
                    for j,cell in enumerate(row)]
                        for i,row in enumerate(graph)]
    

    Because of the way they work, this version doesn't change the graph in-place, but instead creates and returns a new one.