you shortened it, but you broke it too... ;-)

Ned Batchelder ned at nedbatchelder.com
Mon Jan 1 09:13:12 EST 2018


On 12/31/17 8:15 PM, Wu Xi wrote:
> def neighbours(point):
>   x,y = point
>    
>   yield x + 1 , y
>   yield x - 1 , y
>   yield x     , y + 1
>   yield x     , y - 1                 #    this is proof that life can emerge inside of computers and cellular automatons,
>    
>   yield x + 1 , y + 1                 #    and evolve through memory, attack other cells and morph into toads, pulsars, etc..
>   yield x + 1 , y - 1
>   yield x - 1 , y + 1                 #    spray your memory with space alien patterns and life evolution will start in your machine !
>   yield x - 1 , y - 1

This code correctly yields eight new coordinates
>   
>   '''
>   for i in range(-1, 2) :
>          for j in range(-1, 2) :
>              if i != j :
>                  yield x + i, y + j
>
>   '''

This code only yields six of the eight needed.
>   # yield from [(x+i, x+j) for i in [-1,1] for j in [-1,1]]
>   

This code only yields four!

Perhaps this is what you are looking for:

     def neighbors(point):
         x, y = point
         for dx in [-1, 0, 1]:
             for dy in [-1, 0, 1]:
                 if dx == dy == 0:
                     continue
                 yield x + dx, y + dy


--Ned.



More information about the Python-list mailing list