Sysel Sysel - 4 years ago 150
Python Question

python checking surrounding points list of lists index out of range

I'm working on a school project and i'm trying to go through list of lists containing numbers. I'm trying to check all 8 surrounding "block" but i'm getting index out of range exception

filling the list:

for i in range(0, self.sizeX):
temp = []
for j in range(0, self.sizeY):
temp.append(random.randint(0, 100))
self.map.append(temp)


checking the surrounding

def check(self, i, j):
count = 0

if j-1 >= 0 & self.map[i][j-1] > 50:
count += 1

if (j+1) < len(self.map[i]) & self.map[i][j+1] > 50:
count += 1

if i-1 >= 0 & self.map[i-1][j] > 50:
count += 1

if i+1 < self.sizeX & self.map[i+1][j] > 50:
count += 1

if i-1 >= 0 & j-1 >= 0 & self.map[i-1][j-1] > 50:
count += 1

if i+1 < self.sizeX & j-1 >= 0 & self.map[i+1][j-1] > 50:
count += 1

if i-1 >= 0 & j+1 < self.sizeY & self.map[i-1][j+1] > 50:
count += 1

if i+1 < self.sizeX & j+1 < self.sizeY & self.map[i+1][j+1] > 50:
count += 1

return count


it looks like the conditions which check >=0 work but the once which check the size limit don't
btw i had this exact thing working in php with no problem

Answer Source

Your conditions seem to be correct, apart from substituting & (bitwise and) for and (logical and).

I also suggest pulling the tests out as variables; it helps make your code easier to read.

Also note that you are using columnar indexing, ie map[x][y]; it is more common to use row-aligned indexing ie map[y][x]. It is not "wrong" per se, but may be a bit clumsier to work with.

from random import randint

class Map:
    def __init__(self, width, height):
        self.width  = width
        self.height = height
        self.map    = [[randint(0, 100) for y in range(height)] for x in range(width)]

    def neighbor_fn(self, i, j, fn=lambda x: x > 50):
        left     = i - 1
        right    = i + 1
        above    = j - 1
        below    = j + 1
        do_left  = left >= 0
        do_right = right < self.width
        do_above = above >= 0
        do_below = below < self.height
        return (
              (do_left  and do_above  and fn(self.map[left][above]))
            + (do_above               and fn(self.map[i][above]))
            + (do_right and do_above  and fn(self.map[right][above]))
            + (do_left                and fn(self.map[left][j]))
            + (do_right               and fn(self.map[right][j]))
            + (do_left  and do_below  and fn(self.map[left][below]))
            + (do_below               and fn(self.map[i][below]))
            + (do_right and do_below  and fn(self.map[right][below]))
        )
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download