Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Defining boundaries and looping solution in Clear category for Moore Neighbourhood by jrebane
def count_neighbours(grid, row, col):
# Setting up boundaries
start_row = row - 1 if row > 0 else row
end_row = row + 2 if row < len(grid) - 1 else row + 1
start_col = col - 1 if col > 0 else col
end_col = col + 2 if col < len(grid[0]) - 1 else col + 1
# Looping through grid and counting
count = 0
for i in range(start_row, end_row):
for j in range(start_col, end_col):
if grid[i][j] == 1:
count += 1
count = count - grid[row][col]
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"
June 10, 2015