Next / Previous / Contents / Shipman's homepage

5.5. SudokuSolver.__readPuzzle(): Convert puzzle to internal form

This method parses the puzzle in its external form and converts it to a list of integers.

sudosolver.py
# - - -   S u d o k u S o l v e r . _ _ r e a d P u z z l e   - - -

    def __readPuzzle ( self ):
        """Translate the puzzle from external to internal form.

          [ self.givenPuzzle is a string ->
              if self.givenPuzzle is a valid sudoku puzzle ->
                return a list of BOARD_L integers representing
                that puzzle
              else -> raise ValueError ]
        """

Converting the puzzle from string form to a vector of numbers is pretty straightforward. If we ignore all whitespace in the input file, what is left should be a string of exactly BOARD_L characters, each of which should be "." or a digit in string form.

First we smash out all the whitespace and make self.givenPuzzle into a single string. This can be done in one line as a list comprehension:

sudosolver.py
        #-- 1 --
        # [ charList  :=  a list whose elements are the
        #       non-whitespace characters of self.givenPuzzle in
        #       the same order ]
        charList  =  [ c
                       for c in list(self.givenPuzzle)
                       if not c.isspace() ]

At this point we can test for the correct number of characters.

sudosolver.py
        #-- 2 --
        if  len(charList) != BOARD_L:
            raise ValueError, ( "Puzzle has %d nonblank "
                "characters; it should have exactly %d." %
                (len(charList), BOARD_L) )

All that remains is to check each character for validity and convert them to their integer value. This step raises ValueError if any of the characters are not either "." or a digit. See Section 5.6, “SudokuSolver.__readChar(): Translate one input character”.

sudosolver.py
        #-- 3 --
        # [ if each element of charList is either "." or in
        #   the interval ["1", "9"] ->
        #     result  :=  a list of integers corresponding to the
        #         elements of charList consisting of integer 0
        #         where the value is "." and an integer in [1,9]
        #         where the value is a digit
        #   else ->
        #     raise ValueError ]
        result  =  [ self.__readChar ( c )
                     for c in charList ]

        #-- 4 --
        return result

For trace table verification, see Section 7.2, “Trace table: SudokuSolver.__readPuzzle().