Last active
May 30, 2024 22:13
-
-
Save talhaahussain/133fe1a05242858376341d9401f008bb to your computer and use it in GitHub Desktop.
find_neighbours.py -- A simple, elegant way of finding all neighbours for a cell in a grid, using the Moore neighbourhood or the von Neumann neighbourhood. Assumes an inclusive lower bound and exclusive upper bound for x and y. Useful for cellular automata.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def moore(x, y, lower_x, lower_y, upper_x, upper_y): | |
neighbours = [(i, j) for i, j in ((x-1, y-1), (x, y-1), (x+1, y-1), (x-1, y), (x+1, y), (x-1, y+1), (x, y+1), (x+1, y+1)) if lower_x<=i<upper_x and lower_y<=j<upper_y] | |
return neighbours | |
def von_Neumann(x, y, lower_x, lower_y, upper_x, upper_y): | |
neighbours = [(i, j) for i, j in ((x, y-1), (x-1, y), (x+1, y), (x, y+1)) if lower_x<=i<upper_x and lower_y<=j<upper_y] | |
return neighbours |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment