![]() The new function will return true if that number is a valid number that can solve that empty space. Input the board, the possible number, and the position of the empty cell into a new function.These numbers represent the possible numbers that could fill the unsolved space: for num in range( 1, 10): Inside the solve() function, after finding the first empty space, loop through each number from 1 to 9.Using recursion, call the solve() function within itself to try every possible combination of values for all the other spaces as well. ![]() Now that you can identify the first empty space to solve, you will need to try and find an appropriate number to fill that space and solve the puzzle. How to Solve the Puzzle for Each Row, Column, and 3x3 Grid Otherwise, return true to signify that there are no empty spaces left to solve: if not find: Save these values separately into the row and col variables. The find_empty() function returns the cell position in tuple format, for example, (0, 2).In a new function called solve(), use the find function to find the first empty space on the board: def solve (board):.In this case, do not return anything: return None If the script reaches the end of the function, that means the script couldn't find any cells with the value of 0.If the value of the current cell is 0, return the current position of the empty cell: if board = 0:.In a new function called find_empty(), loop through each row and column on the board: def find_empty (board):.These determine which spaces needed solving. You can traverse through the lists to find the spaces that consist of 0s. How to Identify the Empty Spaces to Solve View the puzzle printed onto the screen: python sudoku.py Use the python command to run your Sudoku script.In a command line, navigate to the folder where you stored your python script, for example: cd Desktop.Call the function to print the board: print_board(board).If the column is the last column for that particular row, add a break line, so that the following row appears on a new line: if col = 8: Print the number value stored in the grid.You can also split columns into thirds by checking if the column is divisible by three: for col in range( 9): Within each row, loop through each column.To separate each row into thirds, check if the row is divisible by three, and add a line: if row % 3 = 0 and row != 0:.Inside a new function called print_board, use a for loop to process each row in the grid: def print_board (board):.Add 0s to represent the spaces that need solving: board = [ Each row and column represents the nine numbers across and down the Sudoku puzzle. Inside a new Python script called sudoku.py, store all the values for the 9x9 grid.The code used in this project is available in this GitHub repo under the MIT license.
0 Comments
Leave a Reply. |
Details
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |