A Tale of Two Python Scripts to Solve Sudoku Puzzles

Last year, I wrote a script to help me solve Sudoku puzzles. There were two reasons for this; the first was to improve my Python programming skills and the second was see whether I could actually do it!

Version One of the script used a user generated CSV file as the input, and would look at the grid. First it would look for the first empty cell, then look at the numbers in the same row, then column and then 3×3 grid.

It would create an array from 1 to 9, and then remove any numbers found in the previous search. If there was one number remaining, then it would put that number into the cell.

This process would be repeated until two runs of the process had the same number of spaces i.e. no more numbers were able to be input into the grid.

It would print the Sudoku grid, regardless of whether or not it had been completed.

While this process was largely successful for simple puzzles, it was prone to failure for more difficult puzzles.

One solution which I devised for the unsolved cells problem was to populate any persistently empty cells with a random number from the cell’s array. It would then continue the process to solve it, and if unsolvable, the whole script would start again from scratch.

This solution proved to be unreliable and as such, would continue to process until infinity, without solving the puzzle.

Version Two of the script used a similar process. However there would only be one overall pass of the procedure, and it would always generate a result.

First it would check every cell, and then skip the cell if there was a number already in it. If the cell was empty, then the cell would be filled with a zero value. The check for values in the same row, column and 3×3 grid would be carried out, and then the lowest available number would be put into that cell.

This is different from the first script in that every cell being processed would have a value assigned to it. However, if a future cell was found to be unsolvable, i.e. no numbers could be input into the cell without breaking the rules of Sudoku, then the previous cell would be re-examined with the next available number being input into it.

This means that there would be a back and forth with the puzzle cursor until the puzzle was solved.

Please let me know your thoughts on this or any ways I could improve the puzzle solving process of that scripts!

Leave a Reply

Your email address will not be published. Required fields are marked *