Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Moore Neighbourhood by njm2ody
def count_neighbours(grid, row, col):
result = 0
offset_r = (lambda r: (r-1, r+2) if r > 0 else (r, r + 2))(row)
offset_c = (lambda c: (c-1, c+2) if c > 0 else (c, c + 2))(col)
for r in grid[offset_r[0] : offset_r[1]]:
result += sum(r[offset_c[0] : offset_c[1]])
if grid[row][col] != 0: result -= 1
return result
Jan. 10, 2015