# Array neighbourhoods

Paul McGuire ptmcg at austin.rr.com
Fri Jan 2 16:36:48 CET 2004

```"Daniel Pryde" <ababo_2002 at hotmail.com> wrote in message
news:mailman.42.1072799018.8134.python-list at python.org...
> Hi again.
>
> One thing I forgot to include in my post the other day. I was wondering if
> anyone knew of any fast algorithms for returning the surrounding
neighbours
> of an array element, or even the neighbours of a group of array elements.
>
Try this (requires Python 2.3, since it uses sets).  Can't say how fast it
is, but it handles all cases I can think of (edge effects, disjoint cells,
etc.).  Maybe start with this to get going, then make it faster if it needs
to be.

# matrixNeighbors.py
from sets import Set

def neighborhoodOf(cells, rows, cols):
ret = Set()
if type(cells) == tuple:
row,col = cells
for i in (-1,0,1):
for j in (-1,0,1):
# remove original cell
ret.remove( cells )

elif type(cells) == list:
for cell in cells:
for neighbor in neighborhoodOf(cell,rows,cols):
# remove original cells
ret -= Set( cells )

# remove all entries in ret with negative values,
# or values greater than number of cols/rows
for x,y in ret.copy():
if x < 0 or y < 0 or x >= COLS or y >= ROWS:
ret.remove( (x,y) )

return list(ret)

# define matrix boundaries
ROWS = 4
COLS = 6

print neighborhoodOf( (0,0), ROWS, COLS )
print neighborhoodOf( (COLS-1,ROWS-1), ROWS, COLS )
print neighborhoodOf( (COLS,ROWS), ROWS, COLS )
print neighborhoodOf( [(0,0),(0,1)], ROWS, COLS )
print neighborhoodOf( neighborhoodOf( (1,1), ROWS, COLS), ROWS, COLS )
print neighborhoodOf( neighborhoodOf( (COLS-1,ROWS-1), ROWS, COLS), ROWS,
COLS )
print neighborhoodOf( neighborhoodOf( (COLS,ROWS), ROWS, COLS), ROWS, COLS )

```