[Tutor] Creating a two dimension set
Phil
phillor9 at gmail.com
Mon Nov 1 01:41:28 EDT 2021
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. It was working
perfectly until I tried to make some improvements without saving the
original file. A mistake that I haven't learned from.
> I do not fully understand your use case, partly because your second
> example is not sane Python.
>
> I'm also not sure you mean "set". Can you tell us in more detail what
> you're doing, maybe a very small example programme?
I had originally used 9 x 9 numpy arrays. I then decided to use a list
of lists just as an exercise. The next version used sets because I
wanted to experiment with set intersections. This worked well enough
until I recently found a puzzle that my solver wouldn't solve correctly.
Say I have a 9 x 9 array, or a list of lists, and I want to remove a
number from grid[0][7]. What simple method would I use? I've tried all
sorts of complicated methods but I keep running into problems.
Removing an element from a set or a list is straight forward:
a = {1,2,3,4,5,6,7,8,9}
if 3 in a:
print('found')
a.remove(3)
print(a)
However, removing an element from a list of lists is problematic:
a = [['1','2','3'],['4','5','6']]
a[0][0] = '9'
a.remove('9')
print(a[0][0])
Traceback (most recent call last):
File "/usr/lib/python3.9/idlelib/run.py", line 559, in runcode
exec(code, self.locals)
File "/home/phil/Python/set_test.py", line 29, in <module>
a.remove('9')
ValueError: list.remove(x): x not in list
> 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}
What about removing a number, won't that fail as in a list of lists?
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.
I'm a bit frazzled from driving today, but I'll see if I can experiment
with dictionaries later.
--
Regards,
Phil
More information about the Tutor
mailing list