matrix - Moore neighbourhood in python -
i have grid tuple of tuples integers (1/0), row number , column number cell integers. , have find how many neighbouring cells have neighbours integer.
it's task www.checkio.org, interesting site of learning python.
here code:
def count_neighbours(grid, row, col): grid = () count = 0 pos in ((row - 1, col), (row + 1, col), (row, col - 1), (row, col + 1), (row - 1, col - 1), (row - 1, col + 1), (row + 1, col - 1), (row + 1, col + 1)): if pos == 1: count += 1 homecoming count
the scheme answers me there no neighbours near chosen cell. please explain me what's wrong , give thanks attention!
i see 2 obvious mistakes:
you replaced grid
empty tuple
your code doesn't reference grid
variable @ all, add together 1 count
if pos
equal 1. pos
never equal 1, because setting 1 of series of tuples.
ergo, function always homecoming 0
long row
, col
numeric (and raises exception otherwise).
you need reference grid passed in:
def count_neighbours(grid, row, col): count = 0 pos in ( (row - 1, col), (row + 1, col), (row, col - 1), (row, col + 1), (row - 1, col - 1), (row - 1, col + 1), (row + 1, col - 1), (row + 1, col + 1)): if grid[pos[0]][pos[y]] == 1: count += 1 homecoming count
i'm assuming here grid list of lists representing rows , cells.
next, you'll have handle positions going out of bounds; there no neighbours top of first row, example:
def count_neighbours(grid, row, col): count = 0 x, y in ( (row - 1, col), (row + 1, col), (row, col - 1), (row, col + 1), (row - 1, col - 1), (row - 1, col + 1), (row + 1, col - 1), (row + 1, col + 1)): if not (0 <= x < len(grid) , 0 <= y < len(grid[x])): # out of bounds go on if grid[x][y] == 1: count += 1 homecoming count
python matrix tuples automata neighbours
No comments:
Post a Comment