DEV Community

1Blademaster
1Blademaster

Posted on

2 1

Creating a Sudoku Solver and Generator with Python

Introduction

I recently created a 3-part tutorial on medium on how to create a sudoku engine which was capable of solving and generating sudoku's. A sudoku which has been generated can also be saved as a string, this makes it easier for the exportation of sudoku's. Bear in mind that the algorithms I show you in the tutorial are very greedy since a lot of recursion is used. Here is a link to the Github repo as well if you wanted to browse through the code.

Since this is a 3-part series, I've added links to all the 3 parts below:

  1. Introduction and creation of the solver
  2. Starting the generator 1
  3. Finishing the generator 2

Example Usage

You can use the tutorial to create a Board class which can further be imported into any of your scripts/programs as shown:

if __name__ == '__main__':
board = Board()
question_board_code = board.generateQuestionBoardCode(1) # generates a medium level sudoku
print(question_board_code[0])
code = '300105000060200000008090060050000800800007040071009035000900084704006000902048300'
solved_board_code = Board(code).solveForCode() # solves a hard level sudoku
view raw sudoku.py hosted with ❤ by GitHub

Final Thoughts

If you have any suggestions, advice or questions then please feel free to leave a comment and I shall answer everything.

Thank you for reading! 💖

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs