Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Uncategorized category for Moore Neighbourhood by 1406086056
def count_neighbours(grid, row, col):
num = 0
row_pre = max(0,row-1)
row_pos = min(len(grid),row+2)
col_pre = max(0,col-1)
col_pos = min(len(grid[0]),col+2)
for i in range(row_pre,row_pos):
for j in range(col_pre,col_pos):
if grid[i][j] == 1 and (i != row or j != col):
num += 1
return num
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. 7, 2014
Comments: