Fohlen Fohlen - 1 month ago 7
Python Question

calculate the neighbours of n-dimensional fields in python

When given a matrix of n-dimension and a grid size of 1 I'd like to calculate the nearest neighbours of a field.
Given below is an example for a 2-dimensional field

P = (1,1)

p_neighbours = [(0,0),(2,2),(0,1),(0,2),(1,0),(2,0),(2,1),(1,2)]


Mathematically this can be as easily described as P +/- 1 in a vectorian system (as far as I understand). The size of the n-dimensional neighbour array is described as (n^3)-1
I've already found a pretty good old topic, anyhow I couldn't understand how any of the presented solutions could be extended to a n-dimensional function..

Answer
from itertools import product

def stencil(dim):
    stencils = list(product([-1,0,1], repeat=dim))
    zero = ((0,) * dim)
    stencils.remove(zero)
    return stencils

def neighbours(P):
    stencils = stencil(len(P))
    return [tuple([sum(x) for x in zip(P,s)]) for s in stencils]

P = (4, 4, 4)

print(neighbours(P))