Python function prints the result but Return = None

Asked

Viewed 56 times

-1

I made a function to solve a sudoku game, the function is working correctly (the game is being solved), but the Return of my function is coming as 'None'.

By placing a print on the function it prints the full game board, but it does not return this board if I try to put it into a variable. I can not understand why the function prints the result with 'print(np.Matrix(puzzle))' but if I put a 'Return puzzle' just below it this 'Return' comes as 'None'.

grid = [
[0, 0, 8, 0, 0, 0, 0, 0, 6],
[0, 0, 0, 9, 0, 0, 1, 3, 0],
[0, 0, 5, 0, 1, 3, 0, 0, 0],
[7, 0, 1, 8, 0, 0, 6, 0, 0],
[0, 9, 0, 0, 0, 0, 0, 0, 2],
[0, 0, 0, 1, 9, 0, 0, 0, 0],
[0, 0, 4, 0, 7, 0, 0, 0, 0],
[0, 6, 0, 0, 2, 0, 0, 0, 0],
[8, 0, 0, 0, 0, 0, 4, 7, 0]
]

def possivel(puzzle, lin, col, num):
    if puzzle[lin][col] != 0: # checa se a posição já esta preenchida
        return False
    quad1 = (lin // 3) * 3
    quad2 = (col // 3) * 3
    for x in range(3): # checa o quadrado menor
        for y in range(3):
            if puzzle[quad1+x][quad2+y] == num:
                return False
    for y in range(9): # checa a linha
       if puzzle[lin][y] == num:
           return False
    for x in range(9): # checa a coluna
        if puzzle[x][col] == num:
            return False
    else:
        return True


def resolver(puzzle):
    for lin in range(9):
        for col in range(9):
            if puzzle[lin][col] == 0:
                for numero in range(1,10):
                    valido = possivel(puzzle, lin, col, numero)
                    if valido == True:
                        puzzle[lin][col] = numero
                        resolver(puzzle)
                        puzzle[lin][col] = 0
                return puzzle
    print(np.matrix(puzzle))
    return puzzle

resolver(grid)

1 answer

0

I don’t know what that is np.matrix(puzzle) but if you put one up for print you’ll see that the function is doing what it should:

def resolver(puzzle):
    for lin in range(9):
        for col in range(9):
            if puzzle[lin][col] == 0:
                for numero in range(1,10):
                    valido = possivel(puzzle, lin, col, numero)
                    if valido == True:
                        puzzle[lin][col] = numero
                        resolver(puzzle)
                        puzzle[lin][col] = 0
                return puzzle
    for linha in puzzle: # alterei aqui,
        print(linha)     # aqui
    return puzzle

resposta = resolver(grid)
for linha in resposta: #aqui
    print(linha)       #e aqui

I added a comment in the lines I changed.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.