## Generating list of neighbours, 4x4 board

This is the place for queries that don't fit in any of the other categories.

### Generating list of neighbours, 4x4 board

Hi.

I have just started my Python adventure a few days ago.
Recently, I wrote a simple boggle solver and it works well. However, I find this particular block of code rather clunky. Is there a better (i.e. more pythonic) way of writing it?

The purpose of the code is to return all neighbours of (x,y), on 4x4 board. So, either 8 (middle), 5 (edge) or 3 (corner) neighbours.

Code: Select all
`def get_neighbours(x, y):    offsets = ([-1,-1], [-1,0], [-1,1], [0,-1], [0,1], [1,-1], [1,0], [1,1])    ret_val = list()    for o in offsets:        if x + o[0] >= 0 and y + o[1] >= 0 and x + o[0] <=3 and y + o[1] <= 3:            ret_val.append([x + o[0], y + o[1]])    return ret_val`
Last edited by Mekire on Wed Jan 29, 2014 9:29 am, edited 1 time in total.
Reason: First post lock.
xpil

Posts: 1
Joined: Wed Jan 29, 2014 8:57 am

### Re: Generating list of neighbours, 4x4 board

You should use [] instead of list() to create an empty list.

Code: Select all
`if x >= 0 and x <= 3:`

can be written as:
Code: Select all
`if 0 <= x <= 3:`

You can loop over a list of pairs like this(using tuple unpacking):
Code: Select all
`>>> pairs = [(1, 2), (3, 4), (5, 6)]>>> for first, second in pairs:...     print first, second...1 23 45 6`

Also, generators are an awesome thing.
If you need an actual list, you can always just pass the generator to list()...

With all of that said, your function could look like this:
Code: Select all
`def get_neighbours(x, y):    offsets = ([-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1])    for x_offset, y_offset in offsets:        new_x, new_y = x + x_offset, y + y_offset        if 0 <= new_x <= 3 and 0 <= new_y <= 3:            yield (new_x, new_y)`

Moving offsets outside of the function might also be a good idea, since there's no need to recreate them every time the function is called.
Friendship is magic!

R.I.P. Tracy M. You will be missed.

stranac

Posts: 1475
Joined: Thu Feb 07, 2013 3:42 pm