Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Plain simple solution in Clear category for Moore Neighbourhood by max-lobur
def count_neighbours(grid, row, col):
def normalize(coord, max_val):
if coord < 0:
coord = 0
if coord > (max_val):
coord = max_val
return coord
max_x = len(grid[0]) - 1
max_y = len(grid) - 1
left_x = normalize(col - 1, max_x)
right_x = normalize(col + 1, max_x)
upper_y = normalize(row - 1, max_y)
lower_y = normalize(row + 1, max_y)
count = 0
for cl in range(left_x, right_x+1):
for rw in range(upper_y, lower_y+1):
if (rw, cl) == (row, col):
# Do not check point itself
continue
if grid[rw][cl]:
count += 1
return count
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"
Oct. 27, 2014