Dominic Bou-Samra - 8 months ago 47

Python Question

I have a list of lists, something like

`[[1, 2, 3,],[4, 5, 6,],[7, 8, 9]]`

Represented graphically as:

`1 2 3`

4 5 6

7 8 9

I'm looking for an elegant approach to checking the value of neighbours of a cell, horizontally, vertically and diagonally. For instance, the neighbours of [0][2] are [0][1], [1][1] and [1][2] or the numbers 2, 5, 6.

Now I realise I could just do a bruteforce attack checking every value a la:

`[i-1][j]`

[i][j-1]

[i-1][j-1]

[i+1][j]

[i][j+1]

[i+1][j+1]

[i+1][j-1]

[i-1][j+1]

But thats easy, and I figured I can learn more by seeing some more elegant approaches.

Answer

```
# Size of "board"
X = 10
Y = 10
neighbors = lambda x, y : [(x2, y2) for x2 in range(x-1, x+2)
for y2 in range(y-1, y+2)
if (-1 < x <= X and
-1 < y <= Y and
(x != x2 or y != y2) and
(0 <= x2 <= X) and
(0 <= y2 <= Y))]
>>> print(neighbors(5, 5))
[(4, 4), (4, 5), (4, 6), (5, 4), (5, 6), (6, 4), (6, 5), (6, 6)]
```

I don't know if this is considered clean, but this one-liner gives you all neighbors by iterating over them and discarding any edge cases.