-2
def solve(sudoku):
    for y in range(9):
        for x in range(9):
            if sudoku[y][x] == 0:
                for n in range(1, 10): 
                    if possible(x, y, n):
                        sudoku[y][x] = n
                        solve(sudoku)
                        sudoku[y][x] = 0
                        
                return
    print(np.matrix(sudoku))
    return sudoku

This function prints the solved Sudoku, however print(solve(sudoku)) returns none. Why does the function return none if it can print(sudoku)?

stellasia
  • 5,372
  • 4
  • 23
  • 43
Henri
  • 61
  • 1
  • 3
  • 4
    Because that's what `return` without an argument does. – tripleee Mar 02 '21 at 21:12
  • You'll need to `return solve` to pass the result back up the recursive call chain and finally return that result to the original caller. Otherwise, on the way back up, `return None` and/or `sudoku[y][x] = 0` will give you something other than the solved sudoku, either `None` or a sudoku zeroed out. – ggorlen Mar 02 '21 at 21:18
  • 1
    There is clearly a problem with your algorithm if you want to return a solved matrix, because the only time you ever insert a number into the solution, you *always* then set it back to 0. The resulting matrix can therefore never contain any digits other than 0. – kaya3 Mar 02 '21 at 21:20
  • Turns out the array was incrementally being set back to zero as it was beeing passed back up the recursive chain. I need to fill a completely new array with the solved sudoku at the time of the original print statement. Now it works just fine :) – Henri Mar 07 '21 at 12:03
  • @Henri Glad you worked it out. Feel free to post a [self answer](https://stackoverflow.com/help/self-answer) – ggorlen Mar 07 '21 at 18:22

2 Answers2

0


def solve(sudoku):
    for y in range(9):
        for x in range(9):
            if sudoku[y][x] == 0:
                for n in range(1, 10): 
                    if possible(x, y, n):
                        sudoku[y][x] = n
                        solve(sudoku)
                        sudoku[y][x] = 0
                        
                return # this might be a problem
    print(np.matrix(sudoku))
    return sudoku

0

Your assumptions must be wrong.

If you are saying that print(solve(sudoku)) print None, then this must be what is happening.

The only way for that to happen is if the last return is from the third line from the bottom of your code.

quamrana
  • 37,849
  • 12
  • 53
  • 71