Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Moore Neighbourhood by ribozz
from itertools import chain
def slice_axis(axis, start, end):
"""
Slice axis with respect to original axis boundaries.
"""
return axis[max(start, 0): min(end + 1, len(axis))]
def count_neighbours(grid, row, col):
y = grid # just for convenience
# get all neighbours 3x3 square, with respect to boundaries
subgrid = [
slice_axis(x, col - 1, col + 1)
for x in
slice_axis(y, row - 1, row + 1)
]
my_val = grid[row][col]
# as there is only 1/0 values, we can just count sum of all items in
# our subgrid, except the target point, which also may conatin 1/0 value (my_val)
return sum(chain(*subgrid)) - my_val
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
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"
Nov. 20, 2015
Comments: