Next / Previous / Contents / Shipman's homepage

5.4. SudokuSolver.__init__(): Constructor

The constructor's main job, other than saving its argument values, is to translate the puzzle from its external form (as described in Section 2, “Encoding the puzzle”) to its internal form as a list of 81 integers.

sudosolver.py
# - - -   S u d o k u S o l v e r . _ _ i n i t _ _   - - -

    def __init__ ( self, givenPuzzle, solutionObserver=None,
                   changeObserver=None ):
        """Constructor for SudokuSolver."""

First we save the constructor arguments and initialize the various data structures.

sudosolver.py
        #-- 1 --
        self.givenPuzzle       =  givenPuzzle
        self.solutionObserver  =  solutionObserver
        self.changeObserver    =  changeObserver
        self.nStateChanges     =  0
        self.nSolutions        =  0

The next step is to convert the puzzle from its external form to its internal form, or raise ValueError if it is invalid. See Section 5.5, “SudokuSolver.__readPuzzle(): Convert puzzle to internal form”.

sudosolver.py
        #-- 2 --
        # [ self.givenPuzzle is a string ->
        #     if self.givenPuzzle is a valid sudoku puzzle as a string ->
        #       self.__board  :=  a list of BOARD_L integers
        #                         representing that puzzle
        #     else -> raise ValueError ]
        self.__board  =  self.__readPuzzle()

We need to make a copy of self.__board so we can remember what the puzzle looked like initially. We could use Python's copy module to make the copy, but a “slice of the whole” works just as well.

sudosolver.py
        #-- 3 --
        # [ self.__given  :=  a copy of self.__board ]
        self.__given  =  self.__board[:]

For trace table verification, see Section 7.1, “Trace table: SudokuSolver.__init__().