[Tutor] The Python way and two dimensional lists

Alan Gauld alan.gauld at yahoo.co.uk
Tue Dec 7 04:34:46 EST 2021


On 07/12/2021 07:19, Phil wrote:

> What I have is a 9 x 9 grid and there are three 3 x 3 boxes per line 
> which means that I have nine 3 x 3 boxes in total. 

I believe you are building a model of a Sudoku game?
But from your description it's not clear what data
structure you are using. Please just show it!

For example, do you really have a 9x9 grid - that is,
a list with 81 single elements?

solution = [0,1,2....,79, 80]

Or is it a list with 9 sublists each of 9 elements?

solution = [[0...8],
            [9...17],
....
            [71...80]]

Or is it a list with 9 elements(boxes), each of which
is itself a list with 9 elements

solution = [[0,1,2,9,10,11,18,19,20],[3,4,5,12,13,14...],[6,7,8....]
            [...][...],[...]
            [...],[...],[...,78,79,80]]

or is each box a list with 3 sublists each with 3 elements?


solution = [[[0,1,2],
             [9,10,11],
             [18,19,20]
            ],
            [[3,4,5],....],
            ...
           ]

>From your description you could have any of these structures.

Each box is accessed
> by it's top left coordinates:
> 
>          box_start = [(0, 0), (0, 3), (0, 6),
>              (3, 0), (3, 3), (3, 6),
>              (6, 0), (6, 3), (6, 6)
>              ]

This suggests to me you are using the second option above?
ie a list with 9 sub lists of 9 elements?

> This works but I know that it's not the correct method 

If it works it is "correct" for some definition of correct.

But personally here is how I would tackle your problem.

I'd just use a single list of 81 cells.

I'd then write helper functions to extract the sublists I needed:

def get_cell(table, row, col)

def get_row(table, row_num)

def get_col(table, col_num)

def get_box(table, row_num, col_num)  # or just box_num?

The next problem (based on previous posts) is that your
cells are sets which are immutable, so you need to:
1) create another set of functions for writing back changes
to a cell - tricky...
OR
2) use lists instead of sets because they are mutable.
OR
3) Use OOP and make your cells objects with methods
to add/remove values and using a set internally to
check uniqueness etc. This would be my choice.

Personally, I'd use OOP for the table too, and make the
functions above methods of the table. So you would have
a table object with 81 mutable cells.

But you haven't mentioned OOP up to now so that may be
an extra learning curve you don't want to deal with.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list