Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Moore Neighbourhood by internom
def count_neighbours(grid, x, y):
row = len(grid)
col = len(grid[0])
def inRange(x, y):
return 0 <= x and x < row and 0 <= y and y < col
diff = ((1, -1),
(1, 0),
(1, 1),
(0, -1),
(0, 1),
(-1, -1),
(-1, 0),
(-1, 1))
count = 0
for dx, dy in diff:
if inRange(dx+x, dy+y):
count += grid[dx+x][dy+y]
return count
if __name__ == '__main__':
assert count_neighbours(
((1, 0, 0, 1, 0),
(0, 1, 0, 0, 0),
(0, 0, 1, 0, 1),
(1, 0, 0, 0, 0),
(0, 0, 1, 0, 0),), 1, 2) == 3, "1st example"
assert count_neighbours(((1, 0, 0, 1, 0),
(0, 1, 0, 0, 0),
(0, 0, 1, 0, 1),
(1, 0, 0, 0, 0),
(0, 0, 1, 0, 0),), 0, 0) == 1, "2nd example"
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. 4, 2015
Comments: