Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Second solution in Clear category for Moore Neighbourhood by Butch
from itertools import product
def neighbours(grid, row, col):
"""Returns list of positions of neighbors"""
maxrow = len(grid) - 1
maxcol = len(grid[0]) - 1
dirs = product(range(-1, 2), repeat=2)
neighbors = [(row + d[0], col + d[1]) for d in dirs
if 0 <= row + d[0] <= maxrow and
0 <= col + d[1] <= maxcol and
d != (0, 0)]
return neighbors
def count_neighbours(grid, row, col):
neighbours_pos = neighbours(grid, row, col)
return sum(grid[pos[0]][pos[1]] for pos in neighbours_pos)
June 21, 2015
Comments: