Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Product (row,col) , can be written in one line solution in Clear category for Moore Neighbourhood by sevaader
def count_neighbours(grid, row, col):
from itertools import product
SIZE_Y = len(grid[0]) if grid else 0
SIZE_X = len(grid)
X,Y = [row-1, row, row+1], [col-1, col, col+1]
return sum([ grid[x][y] for x,y in product(X,Y) if (x,y) != (row,col) and 0 <= x < SIZE_X and 0 <= y < SIZE_Y ])
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
assert count_neighbours(((1, 1, 1),
(1, 1, 1),
(1, 1, 1),), 0, 2) == 3, "Dense corner"
assert count_neighbours(((0, 0, 0),
(0, 1, 0),
(0, 0, 0),), 1, 1) == 0, "Single"
Dec. 26, 2014
Comments: