0

I thought I had list comprehensions more or less figured out but then I was presented with this line of code from another question.

Pythonic and efficient way of finding adjacent cells in grid

I've changed the code to just return the 8 tuples that make up the adjacent tiles (when added to our current tile).

[(i, j) for i in (-1,0,1) for j in (-1,0,1) if i != 0 or j != 0]

produces:

[(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)]

The statement actually makes sense to me except for the last part where the conditional is made:

if i != 0 or j != 0

If we're trying to find adjacent cells, and we want to omit the cell that we are in, shouldn't the conditional part read AND instead of OR?

Like this:

if i != 0 and j != 0

Instead if I put AND in there, I get only these tuples returned:

(-1, -1), (-1, 1), (1, -1), (1, 1)

Just seems counter intuitive to me.

Community
  • 1
  • 1
  • Assuming your tile is cell (0,0) then you want any of the surrounding cells. These include (-1,0), (1,0), (0, -1) and (0, 1). The only cell you want to exclude is (0,0). As a result you want either one of either x or y to be non zero. (0,0) doesn't satisfy this. – elParaguayo Jan 09 '15 at 17:11
  • Note that by DeMorgan's law, `if i != 0 or j != 0:` is equivalent to `if not ( i == 0 and j == 0):` - that makes it a little better to understand why it was written that way in light of the above comment by @elParaguayo – twalberg Jan 09 '15 at 18:34
  • Okay thankyou twalberg, you explained that perfectly. In retrospect I can think of a few ways I could of found that answer without bugging you guys but thanks nonetheless! – Curtis Sherwood Jan 09 '15 at 19:48

0 Answers0