sudoku solver - Some additions

August Additions

So, now that the sudoku algo is in place, it would be nice to make it usable. I want to add a couple of things:

  • Making it pretty - give the display of the puzzles some love
  • System for inputting sudokus you find online/in RL.
  • Ability to store puzzles (and solutions)
  • Ability to have a little demo mode
  • Diplay how long it took to find the solution.
  • and a menu system to tie it all together.

Making it pretty

First thing I touched - just a small function Sudoku.display_board() to print out the information in a visually pleasing manner based on an example I found through Google Image search.

def display_board(puzzle):
        print('\n')
        print('+-------+-------+-------+')
        for y in range(0, len(puzzle)):
            print(f'| {puzzle[y][0]} {puzzle[y][1]} {puzzle[y][2]} ' +
                    f'| {puzzle[y][3]} {puzzle[y][4]} {puzzle[y][5]} ' +
                    f'| {puzzle[y][6]} {puzzle[y][7]} {puzzle[y][8]} |')
            if y in [2, 5, 8]:
                print('+-------+-------+-------+')

The way the func is designed allows for partial boards to be printed - this was kind of accidental but helps with the feedback of information when inputting the board - see below.

Puzzle Input

So in an ideal world, I would just want to be able to take a picture of a sudoku, or screenshot, and have that be solved. But that is a little beyond me for now.

Instead, I used an input function that asks you to type in the puzzle row by row, with 0 representing missing values. It is not the most graceful solution perhaps, but it does allow me to quite easily feed in the input into the solution function.

def input_puzzle():
        puzzle = []
        input_msg = 'Input the known values.\nIf value is blank, input 0.\nEg. 530070000\n'
        while len(puzzle) < 9:
            valid = False
            while not valid:
                new_row = input(input_msg)
                puzzle.append(Sudoku.convert_row(new_row))
                valid = Sudoku.validate_row(new_row, puzzle)
                if not valid:
                    puzzle.pop()
                    print('Try Again\n\n')
        return puzzle

Convert_row turns the input into a list.

The one thing I regret is having to validate each row after it is typed. It is very annoying because most of the time I got the row right, and repeatedly validating got tedious. Then again, when a mistake is made, it mean not only having to start the puzzle again, but also having to complete input of any further rows. Which would be really shit. So its a judgement call between a small amount of constant annoyance or rare catastrophes. Hmmm.

You can't even press Enter several times... that will just register the row as incomplete. Perhaps it should recognise that if you're just tapping Enter, you've given up on the process.

[Rest later...]

21