-2

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
Jordan
  • 902
  • 2
  • 10
  • 37
  • Please post the full error traceback! It's the part that tells where the problem is. – Klaus D. Nov 24 '14 at 02:31
  • you're checking "if x is in bound OR y is in bounds". `s/or/and/`. – ch3ka Nov 24 '14 at 02:33
  • @ck3ka: `s/comment/answer/` – DSM Nov 24 '14 at 02:34
  • I did change the ORs to ANDs, that was a problem thank you. But it is still throwing the IndexError, just on a different tuple as a test. File "test.py", line 8, in count_neighbours if grid[row+x][col+y] == 1: IndexError: tuple index out of range – Jordan Nov 24 '14 at 02:48

1 Answers1

0

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)):
dkamins
  • 21,450
  • 7
  • 55
  • 59
  • Someone suggested that in the comments on the previous answer and it definitely fixed that test. But when I put in a different tuple it still throws the same exact error. – Jordan Nov 24 '14 at 03:03