Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Moore Neighbourhood by wo.tomasz
def count_neighbours(grid, row, col):
row_no = len(grid)
col_no = len(grid[0])
rs = row - 1 if row > 0 else 0
re = row + 1 if row + 1 < row_no else row_no - 1
cs = col - 1 if col > 0 else 0
ce = col + 1 if col + 1 < col_no else col_no - 1
return sum([sum(grid[i][cs:ce+1]) for i in range(rs, re+1)]) - grid[row][col]
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. 18, 2021
Comments: