Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Simple approach with itertools.product() solution in Clear category for Moore Neighbourhood by exoarn2
import itertools
def count_neighbours(grid, row, col):
# Create iteratior with relative x,y coord or all 8 possible neigbours
# and the position itself [0, 0] !
offsets = itertools.product([-1, 0, 1], repeat=2)
# correction for [0, 0] offset which can be the piece itself
neighbour_count = -grid[row][col]
for offset in offsets:
new_row = row + offset[0]
new_col = col + offset[1]
if is_in_board(grid, new_row, new_col) and grid[new_row][new_col]:
neighbour_count += 1
return neighbour_count
def is_in_board(grid, row, col):
# check if given coordinate is withind dimensions of the board
return row >= 0 and row < len(grid) and col >= 0 and col < len(grid[row])
April 4, 2015