Mailer Daemon
Mailer Daemon

Reputation: 57

Finding value in a matrix using python

I am getting the error 'int object is not iterable' on this method in my class. Someone assist me find the bug as I can't see what I am doing wrong

def find(self, val): #finds value in matrix
    if 0 <= val <= 8:
        for i,j in range(3):
            #for j in range(3):
            if self.matrix[i][j] == val:
               return i, j
    return None 

Upvotes: 0

Views: 95

Answers (2)

Manuel
Manuel

Reputation: 706

def find(self, val):  # finds value in matrix
if 0 <= val <= 8:
    for i in range(3):
        for j in range(3):
            if self[i][j] == val:
                return i, j
return None

Example:

self = [[2,1,2],[1,6,4],[0,0,2]]
val = 4

i, j = find(self, val)

print(i)
print(j)

Print: 1 2

If define self as matrix of numpy:

def find(self, val):  # finds value in matrix
    if 0 <= val <= 8:
        for i in range(3):
            for j in range(3):
                if self.item((i, j)) == val:
                    return i, j
    return None

Upvotes: 1

Houhou
Houhou

Reputation: 1

here is the part of your code that is causing the error

for i,j in range(3)

the python's built-in range function generates a sequence of number that are then assigned to one variable, but you're using two variables instead . This is how your code should be :

def find(self, val): #finds value in matrix
    if 0 <= val <= 8:
        for i in range(3):
            for j in range(3):
                if self.matrix[i][j] == val:
                    return i, j
    return None 

Upvotes: 0

Related Questions