user1888493
user1888493

Reputation:

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

Upvotes: 2

Views: 3655

Answers (5)

martineau
martineau

Reputation: 123473

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.

Upvotes: 1

IamAlexAlright
IamAlexAlright

Reputation: 1500

Not an answer to your question but here is a 'easy' way to do it

return [[0 if i2==i else 1 if item == 0 else 0 for i2,item in enumerate(row)] for i,row in graph]

Upvotes: 0

Manas Paldhe
Manas Paldhe

Reputation: 776

It is fairly simple. Basically you need to find the number of elements in the array

 mylist = [1,2,3,4,5]
 len(mylist) # returns 5
 #this gives the number of elements.
 rows=len(g1) # get the number of rows
 columns=len(g1[0]) #get the number of columns
 #Now iterate over the number of rows and columns
 for r in range(0, rows):
    for c in range (0,columns):
       if (r==c):
              g1[r][c]=0
       else:
           g1[r][c]=1-g1[r][c]

Hope that helps

Upvotes: 0

kaspersky
kaspersky

Reputation: 4097

The mistake is in your "while the current row has a value". This will be always true while you will iterate through the elements in the row, and when you'll reach past them, you'll get the exception.

Instead, use:

for r in range(len(graph):
    for c in range(len(graph[0]):
        # do something with graph[r][c]

Upvotes: 0

Hyperboreus
Hyperboreus

Reputation: 32429

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

You have to make sure first, that both indices exist, prior to comparing its -possible- value to 0 or 1. This causes your exceptions. To invert your matrix you would want to do something like

for row in graph:
    for idx, v in enumerate (row):
        row [idx] = 0 if v else 1

Upvotes: 0

Related Questions