Compare Solving Sudoku in Python and Golang

In this article I share my code to solve sudoku puzzle in python and golang and check timing results.

Photo by Jonathan Ybema on Unsplash

Let’s review the original algorithm to solve a sudoku. First consider the input. I prefer to get a string of integers as input, I think it’s an easy way to get it from user. So we need to convert our string to an 9*9 matrix of integers.

Now it’s time to solve our matrix. I prefer to solve it with a recursive function. For this we need to develop some functions to help us in the main function to solve the puzzle as below.

A function to move to next position and check the end of puzzle. I name it go_to_next_position() and it would get the index of current position and will forward us to next position, and checks that have we visited all positions or not.

A function to check available numbers for a position. I name it check_available_candidates(). It would check the row, column and 3*3 square of current position and return a list of available numbers for current position.

The last function will be a double check of solved puzzle, and will check puzzle to be solved correctly. I will name it check_sudoku().

The main function will be named as solve(). It’s a recursive function. It will start from (0, 0) and in each position first it gets a copy from current state of puzzle. Then checks the current position value. If it is a zero value so it will check for available candidates and in a for loop will continue to solve the puzzle. If it’s not a zero value it will try to solve the puzzle in next position. It will end when there is no more available candidates or when it traversed all positions.

Python Code

Golang Code

And in the end let’s compare python and golang in timing. I test both with a simple and a hard sudoku puzzle. Although I love python and developing in python was by far easier than golang, believe it or not the results will show the winner.

I test both in below environment. With Python 3.8 and Golang 1.15.5.

Test environment

And results:


Backend software engineer who loves to learn. I am experienced in Python, Django, DRF, Neo4j, PostgreSQL and I am a newbie gopher :).