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

John Machin sjmachin at lexicon.net
Mon Feb 12 02:20:11 EST 2007


On Feb 12, 4:24 pm, Samuel Karl Peterson
<skpeter... at nospam.please.ucdavis.edu> wrote:
> C-like way to do it, (warning, untested in python):
>
> for i in range(8):
>     for j in range(8):
>         for offset_i in range(-1,2):
>             for offset_j in range(-1, 2):
>                 row = i + offset_i
>                 col = j + offset_j
>                 if (row < 0 or row > 7) or (col < 0 or col > 8) \
>                    or ((row,col) == (i,j)):
>                     continue
>                 # else do something with board[row][col]
>
> I realize this is gross and un-Pythonic and does the same thing

It's also just a little bit inefficient. Never mind the algorithm,
we'll talk about that later. Let's just improve the code a little:

side_range = range(8)
delta_range = range(-1, 2)
for i in side_range:
    for offset_i in delta_range:
        row = i + offset_i
        if not (0 <= row <= 7): continue
        for j in side_range:
            for offset_j in delta_range:
                if not offset_i and not offset_j: continue
                col = j + offset_j
                if not(0 <= col <= 7): continue
                # *now* it's safe to do something
                # with (row, col)

Such hoisting of code out of inner loops is done for you by a C
compiler -- Python assumes you know what you are doing :-)

Now for the algorithm: all of that testing to see if you are about to
sail off the end of the world is a bit ugly and slow. You can use bit-
bashing, as Paul suggested, even though it's on Steven D'Aprano's list
of 6 deadly sins :-)

Another approach that has been used is to have a 9 x 9 storage area;
the squares off the edge contain a value that is neither "empty" nor
any value that represents a piece. So with careful coding, they
automatically fail tests like "can I capture the piece on this
square" [no, it's not a piece] and "can I move here" [no, it's not
empty]. If the game is chess, you need 10 x 10 to cater for those
pesky knights.

Cheers,
John




More information about the Python-list mailing list