Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
max_min_max_min. count solution in Clear category for Moore Neighbourhood by furtadobb
def count_neighbours(grid, row, col):
count = 0
rows = [max(row - 1, 0), row, min(row + 1, len(grid) - 1)]
cols = [max(col - 1, 0), col, min(col + 1, max((len(x) for x in grid)) - 1)]
for h in range(min(rows), max(rows) + 1):
for v in range(min(cols), max(cols) + 1):
if grid[h][v] == 1 and (h != row or v != col):
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"
Sept. 11, 2020