Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
2 solutions (1 vs 2 lines) solution in Clear category for Moore Neighbourhood by CDG.Axel
def count_neighbours(grid, row, col):
return sum(sum(line[col - bool(col):col + 2]) for line in grid[row - bool(row):row + 2]) - grid[row][col]
"""
# set alternative
def count_neighbours(grid, row, col, rng=(-1, 0, 1)):
chips = {(x, y) for y, line in enumerate(grid) for x, v in enumerate(line) if v} - {(col, row)}
return len({(col + x, row + y) for x in rng for y in rng} & chips)
"""
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"
Feb. 26, 2022
Comments: