Why and where is this IndexError occurring?

64 views Asked by At

I am trying to do a check on a position to see if the positions around it are both valid indexes as well as visually next to each other on a grid system(hence the count_neighbor function name). On line 8, I am getting an IndexError meaning the if statement before it isn't correctly filtering out the invalid and/or not next to each other cells it is testing. I can't seem to figure out why..

def count_neighbours(grid, row, col):
    count = 0
    neighbors = ((1,0),(1,-1),(1,1),
                 (0,1),(0,-1),
                 (-1,0),(-1,-1),(-1,1))
    for x,y in neighbors:
        if row+x >= 0 and col+y >= 0 and row+x < len(grid)-1 and col+y < len(grid)-1:
            if grid[row+x][col+y] == 1:
                count += 1
    return count

print count_neighbours(((1,0,1,0,1),
                        (0,1,0,1,0),
                        (1,0,1,0,1),
                        (0,1,0,1,0),
                        (1,0,1,0,1),
                        (0,1,0,1,0)),5,4)

Error:

Traceback (most recent call last):
  File "test.py", line 17, in <module>
    (0,1,0,1,0)),5,4)
  File "test.py", line 8, in count_neighbours
    if grid[row+x][col+y] == 1:
IndexError: tuple index out of range
1

There are 1 answers

1
dkamins On

Your if statement is not strict enough. Currently using or:

if ((row+x >= 0 or col+y >= 0) 
    and
    (row+x < len(grid)-1 or col+y < len(grid)-1)):

Change the ors to ands:

if ((row+x >= 0 and col+y >= 0) 
    and
    (row+x < len(grid)-1 and col+y < len(grid)-1)):