Problem with list of dicts and copying

Cameron Pulsford cameron.pulsford at gmail.com
Wed Jul 8 13:09:43 EDT 2009


Hello all, I'm redoing a sudoku solver of mine and I ran into an issue with
lists of dicts. Bear with me for a second before I get to the actual
problem... I'm representing the board as a dictionary, where the keys are
(x, y) positions, and the values are candidates. So my program goes along
picking numbers from the list of candidates and then propagating the
constraints. So it might place a 6, which would then remove 6 as a candidate
from that row column and grid. However, that might leave a spot with no
candidates, which means we placed a legal but not correct number. This is
where my problem arises. I keep a running list of the boards which is
updated every time I find a legal number that doesn't invalidate the boards.
I add onto this list by doing "boards.append(self.board.copy())". When I
place a legal but invalid number I do "self.board = boards[-1].copy()" to
return the board to the last known good state. And when I completely exhaust
the candidates for a spot and must backtrack to a different spot (instead of
simply trying a different candidate of the current spot) I do "self.board =
boards[-1].copy() and then del boards[-1]"
Basically my boards list should be copies of good boards, and when I need to
refresh the current board, I want to pull off a copy of the correct one.
Essentially (after watching the debugging output) it looks like this isn't
happening. I am always modifying the same board. The algo follows, and I can
post the rest of the code if necessary. So am I using the dict.copy() wrong?
Am I guessing I have a tricky problem with the "=" in "self.board =
boards[-1].copy()"

    def solve(self):
        previousValue = dict((blank, 0) for blank in self.blanks())
        self.fillInCandidates()
        continuing, boards, guesses = False, [self.board.copy()], 0
        while len(self.blanks()) > 0:
            if continuing == False:
                cp = self.mrv()
            continuing = False
            nl = self.nextLegal(cp, previousValue[cp])
            previousValue[cp] = nl
            if nl != 0:
                self.board[cp] = nl
                guesses += 1
                self.update(nl, cp[0], cp[1])
                if self.isNotLegal():
                    continuing = True
                    self.board = boards[-1].copy()
                else:
                    boards.append(self.board.copy())
            else:
                previousValue[cp] = 0
                self.board = boards[-1].copy()
                del boards[-1]
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20090708/18d7843a/attachment.html>


More information about the Python-list mailing list