user1862529
user1862529

Reputation: 23

Python Matrix Neighbor Checking

I have a 7*7 matrix containing 0s and 1s in which each (x,y) will be checked for how many of its neighbors are a 1. I am a beginner to python, and will only be using basic programming procedures.

I have:

for x in range(rows):
        for y in range(cols):
            lives = 0
            lives = neighbors(matrix, rows, cols)

def neighbors(matrix, rows, cols):

            if matrix[x][y+1] == 1:
                lives += 1
            if matrix[x-1][y+1] == 1:
                lives += 1
            #All 8 positions are checked like this
    return lives

I am getting the ol indexing error. This seems like a very simple problem I just can't seem to figure out how to fix it.

Upvotes: 2

Views: 4990

Answers (1)

Bjerva
Bjerva

Reputation: 223

First of all, the index error occurs when you do y+1. Since you are going in the range of the amount of cols, this will end up being cols+1, which is out of range. What you can do is use a try-except block, or make sure it doesn't get out of range through only looping to cols-1.

Additionally your function definition is redundant, since you don't use all your input parameters, and you access the x and y variables in the global scope. The easiest thing to do is probably just to remove the definition and the return-statement.

This should work:

for x in range(rows):
    for y in range(cols-1): #Loop until the second to last element.
        lives = 0
        if matrix[x][y+1] == 1:
            lives += 1
        if x == 0:  #You probably don't want to check x-1 = -1
            continue 
        if matrix[x-1][y+1] == 1:
            lives += 1

Upvotes: 1

Related Questions