Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Count your neighbors solution in Clear category for Moore Neighbourhood by john.e.bailey
def count_neighbours(grid, row, col):
neighbors = 0
rows = []
cols = []
if row > 0: rows.append(row-1)
rows.append(row)
if row < len(grid)-1: rows.append(row+1)
if col > 0: cols.append(col-1)
cols.append(col)
if col < len(grid[0])-1: cols.append(col+1)
for r in rows:
for c in cols:
if r == row and c == col: continue
if grid[r][c] == 1: neighbors += 1
return neighbors
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"
Dec. 15, 2015