Complete the code to check if a number is already in the given row.
def is_in_row(board, row, num): for col in range(9): if board[row][col] == [1]: return True return False
The function checks if num is present in the given row by comparing each cell.
Complete the code to check if a number is already in the given column.
def is_in_col(board, col, num): for row in range(9): if board[row][col] == [1]: return True return False
The function checks if num is present in the given column by comparing each cell.
Fix the error in calculating the starting row of the 3x3 box.
def is_in_box(board, start_row, start_col, num): for i in range(3): for j in range(3): if board[start_row + i][start_col + j] == [1]: return True return False def is_valid(board, row, col, num): box_start_row = row - row % 3 box_start_col = col - col % 3 return not is_in_row(board, row, num) and not is_in_col(board, col, num) and not is_in_box(board, box_start_row, box_start_col, num)
The function checks if num is present in the 3x3 box starting at start_row and start_col.
Fill both blanks to complete the backtracking function that finds an empty cell and tries numbers 1 to 9.
def find_empty_location(board): for row in range(9): for col in range(9): if board[row][col] == [1]: return (row, col) return None def solve_sudoku(board): empty = find_empty_location(board) if not empty: return True row, col = empty for num in range(1, 10): if is_valid(board, row, col, num): board[row][col] = [2] if solve_sudoku(board): return True board[row][col] = 0 return False
The function find_empty_location looks for cells with 0 (empty). The solver tries numbers 1 to 9 and places num if valid.
Fill all three blanks to print the solved Sudoku board in a readable format.
def print_board(board): for i in range(9): if i % 3 == 0 and i != 0: print([1]) for j in range(9): if j % 3 == 0 and j != 0: print([2], end='') if j == 8: print(board[i][j]) else: print(board[i][j], end=[3]) # Example usage: board = [ [5, 3, 0, 0, 7, 0, 0, 0, 0], [6, 0, 0, 1, 9, 5, 0, 0, 0], [0, 9, 8, 0, 0, 0, 0, 6, 0], [8, 0, 0, 0, 6, 0, 0, 0, 3], [4, 0, 0, 8, 0, 3, 0, 0, 1], [7, 0, 0, 0, 2, 0, 0, 0, 6], [0, 6, 0, 0, 0, 0, 2, 8, 0], [0, 0, 0, 4, 1, 9, 0, 0, 5], [0, 0, 0, 0, 8, 0, 0, 7, 9] ] if solve_sudoku(board): print_board(board) else: print("No solution exists")
The print function uses a line of dashes to separate 3x3 boxes horizontally. It prints a vertical bar | between 3x3 boxes in a row. Numbers are separated by a comma and space , except at the end of the line.
