searching a list of lists as a two-dimensional array?

Gabriel Genellina gagsl-py at yahoo.com.ar
Mon Feb 12 00:48:50 EST 2007


En Mon, 12 Feb 2007 02:24:54 -0300, Samuel Karl Peterson  
<skpeterson at nospam.please.ucdavis.edu> escribió:

> James Stroud <jstroud at mbi.ucla.edu> on Sun, 11 Feb 2007 16:53:16 -0800
> didst step forth and proclaim thus:
>
>> agent-s wrote:
>> > Basically I'm programming a board game and I have to use a list of
>> > lists to represent the board (a list of 8 lists with 8 elements each).
>> > I have to search the adjacent cells for existing pieces and I was
>> > wondering how I would go about doing this efficiently. Thanks

> Wow, maybe it's just me (I'm a pretty bad programmer) but this is
> where list comprehensions begin to look unreadable to me.  Here's a
> C-like way to do it, (warning, untested in python):

Just for fun, and to add one more way. This is a generator for adjacent  
indexes, that can be used to search for occupied cells, for locating a  
suitable next move, or whatever:

py> def adj(i, j):
...   for ni in (i-1, i, i+1):
...     if ni not in range(8): continue
...     for nj in (j-1, j, j+1):
...       if nj not in range(8): continue
...       if ni!=i or nj!=j:
...         yield ni,nj
...
py>
py> print list(adj(4,3))
[(3, 2), (3, 3), (3, 4), (4, 2), (4, 4), (5, 2), (5, 3), (5, 4
py> print list(adj(7,3))
[(6, 2), (6, 3), (6, 4), (7, 2), (7, 4)]
py> print list(adj(4,7))
[(3, 6), (3, 7), (4, 6), (5, 6), (5, 7)]
py> print list(adj(0,7))
[(0, 6), (1, 6), (1, 7)]

-- 
Gabriel Genellina




More information about the Python-list mailing list