Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Indicies first solution in Clear category for Moore Neighbourhood by kkkkk
def count_neighbours(grid, row, col):
# Create tuples of potential neighbors.
indices = ((row-1, col-1), (row-1, col), (row-1, col+1), # above
(row, col-1), (row, col+1), # left and right
(row+1, col-1), (row+1, col), (row+1, col+1)) # below
grid_width = len(grid[0])
grid_length = len(grid)
count = 0
for (tmp_row, tmp_col) in indices:
# If the tuple is within the grid, accumulate the cell's value.
if tmp_row >= 0 and tmp_row < grid_length and \
tmp_col >= 0 and tmp_col < grid_width:
count += grid[tmp_row][tmp_col]
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"
Jan. 10, 2015
Comments: