Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
3 Solutions in 1 solution in Clear category for Moore Neighbourhood by Alex_4444D
count_neighbours=lambda g,r,c:sum(sum(x[max(c-1,0):c+2])for x in g[max(r-1,0):r+2])-g[r][c]
#or
f = lambda g: ((0,)*(len(g[0])+2),)+tuple((0,)+x+(0,) for x in g)+((0,)*(len(g[0])+2),)
count_neighbours = lambda g, r, c: sum(f(g)[r][c:c+3]+f(g)[r+2][c:c+3])+f(g)[r+1][c]+f(g)[r+1][c+2]
#or
def count_neighbours(grid, row, col):
rows = range(max(0, row - 1), min(row + 2, len(grid)))
cols = range(max(0, col - 1), min(col + 2, len(grid[0])))
return sum(grid[r][c] for r in rows for c in cols) - 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"
Nov. 8, 2021
Comments: