Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Uncategorized category for Moore Neighbourhood by quis20
def count_neighbours(grid, row, col):
result = 0
size_r = 3
size_c = 3
start_r = row-1
start_c = col-1
grid_max_r = len(grid)-1
grid_max_c = len(grid[0])-1
if start_r < 0:
start_r = 0
size_r-=1
if start_c < 0:
start_c = 0
size_c-=1
for r in range(size_r):
cur_r = start_r+r
if cur_r > grid_max_r:
break
for c in range(size_c):
cur_c = start_c+c
if cur_c > grid_max_c:
break
if grid[cur_r][cur_c] == 1:
result+=1
if grid[row][col] == 1:
result-=1
return result
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"
Jan. 24, 2016