2-dimensional data structures

Diez B. Roggisch deets at nospam.web.de
Sat Feb 18 17:38:14 EST 2006


> However, I wondering how to approach the search of the nine regions of 
> the grid. I am thinking of producing another nested list, again 9x9 to 
> store the contents of each region, and to update this after each pass 
> through -and update of- the main grid (row and column).
> 
> I am not sure how to most efficiently identify which region any given 
> square on the grid is actually in - any thoughts, for those that have 
> done this? - I don't want a massive list of IF conditionals if I can 
> avoid it.

The question is not so much which region a give square is in, but more 
which square contains which fields. If we assume that you number your 
squares row-wise (top-left zero, top-right 3, bottom-right 9), this 
function computes the field indices that a given square is composed of:

def scoords(n):
     square_row = n / 3
     square_col = n % 3
     start_row = square_row * 3 # ( this is _not_ n!!)
     start_column = square_col * 3
     for x in xrange(start_column, start_column + 3):
         for y in xrange(start_row, start_row + 3):
             yield (x,y)

print list(coords(4))

Regards,

Diez



More information about the Python-list mailing list