[Tutor] Creating a two dimension set

Cameron Simpson cs at cskk.id.au
Mon Nov 1 04:59:24 EDT 2021


On 01Nov2021 15:41, Phil <phillor9 at gmail.com> wrote:
>
>On 1/11/21 06:08, Cameron Simpson wrote:
>>On 31Oct2021 15:56, Phil <phillor9 at gmail.com> wrote:
>Thank you Cameron for answering my fool question. I've moved from our 
>camping site with a frustrating Internet connection
>>>As an example, if I wanted to create a two dimension list I would write:
>>>
>>>num_rows = 9
>>>num_cols = 9
>>>
>>>self.solution = [[None] * num_cols for _ in range(num_rows)]
>>Keeping in mind that this is a list of lists. Also, you're preallocating
>>num_cols*nul_rows of storage. That can be wasteful if you're not filling
>>much of it in.
>
>This is a 9 x 9 grid that I use to solve Sudoku puzzles.

Tiny then. Don't worry about the space; do the simplest thing.

>It was working perfectly until I tried to make some improvements 
>without saving the original file. A mistake that I haven't learned 
>from.

Use revision control. It's just great!

>I had originally used 9 x 9 numpy arrays.

I guess that lets you do the grid directly. But numpy is kind of 
overkill for Sudoku in most regards.

Your followon post has a list of lists of sets, which covers things off 
nicely.

[...]
>>Might I suggest a dict indexed by a 2-tuple of (row,col)?
>
>Thank you for your detailed description of dictionaries, I'm not sure 
>that a dictionary would be suitable for my case. Can a dictionary 
>contain a set rather than a single number, it probably can? Like this:
>
>grid = {}
>grid[0,0] = {1,2,3,4,5,6,7,8,9}

Yes. List elements are Python references, just like any other Python 
variable. Referencing a set is no different to referencing a str or an 
int.

>What about removing a number, won't that fail as in a list of lists?

List of lists of sets. grid[0,0].remove(3)

>Each cell contains a set of candidate numbers (1 to 9). I run through 
>a set (not to be confused with a mathematical set) of rules removing 
>numbers from the candidates until the puzzle is solved.

Python sets are deliberately quite similar mathematical sets.

Cheers,
Cameron Simpson <cs at cskk.id.au>


More information about the Tutor mailing list