Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Moore Neighbourhood by nlaurance
def count_neighbours(grid, row, col):
allowed_rows = range(len(grid))
allowed_cols = range(len(grid[0]))
row_above = row - 1
row_below = row + 1
col_before = col - 1
col_after = col + 1
cells_to_check = ((row_above, col_before),
(row_above, col),
(row_above, col_after),
(row, col_before),
(row, col_after),
(row_below, col_before),
(row_below, col),
(row_below, col_after))
def evaluate(pos):
r, c = pos
if all(((r in allowed_rows),
(c in allowed_cols))):
return grid[r][c]
return 0
return sum(map(evaluate, cells_to_check))
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"
June 29, 2015