Python returning none instead of an array - python-3.x

I made some code to solve a sudoku puzzle recursively, however when i go to return the output of the puzzle it returns none instead of the output, however printing the result at the end shows the correct solution
def sudoku(puzzle):
for y in range(9):
for x in range(9):
if(puzzle[y][x] == 0):
for n in range(1,10):
if possible(puzzle,x,y,n):
puzzle[y][x] = n
sudoku(puzzle)
puzzle[y][x] = 0
return
print(puzzle)
return puzzle
def possible(puzzle,x,y,n):
for i in range(9):
if (puzzle[y][i] == n):
return False
for i in range(9):
if (puzzle[i][x] == n):
return False
x0 = (x//3)*3
y0 = (y//3)*3
for i in range(3):
for j in range(3):
if(puzzle[y0 + j][x0 + i] == n):
return False
return True
When I run this code, the correct solution gets printed to the console but the returned output is none. I suspect that this is caused by the line return, but I don't know how to go back to the previous level of recursion without this.

Related

How to create a perfect number function using lists

My perfect number function is not working as intended :(. It prints false even though it should print true :(
def perfect_check(number):
z = []
for i in range(1, number):
if number % i == 0:
z.append(i)
if sum(z) == number:
return True
else:
return False
print(perfect_check(6))
def perfect_check(number):
z = []
for i in range(1, number):
if number % i == 0:
z.append(i)
if sum(z) == number:
return True
else:
return False
print(perfect_check(6))
You have put the if-else statement inside your for loop. It should be outside the for loop. Then, your code will work correctly.

how to create an impossible sudoku detector?

I'm making a sudoku solver on pygame, using backtracking. It's working, both the backtracking and the gui, however, when the user tries to solve an impossible puzzle, the game freezes.
I want to make a modification to my algorithm that, when the puzzle is impossible, the algorithm detects it, warning the user and reseting the board.
For now, this is the main code for the board class.
class Board:
solvedBoard = [[0 for i in range(9)] for j in range(9)]
gameRunning = True
def __init__(self):
self.tabuleiro = [[0 for i in range(9)] for j in range(9)]
def reset(self):
self.tabuleiro = [[0 for i in range(9)] for j in range(9)]
self.gameRunning = True
def show(self):
for i in self.tabuleiro:
for j in i:
print(j, end = ' ')
print('')
def setCell(self, linha, coluna, valor):
self.tabuleiro[linha][coluna] = valor
def isFull(self):
for i in range(9):
for j in range(9):
if self.tabuleiro[i][j] == 0:
return False
return True
def numberPossibilities(self, linha, coluna):
possible = [1 for i in range(10)]
#horizontal check
for col in range(9):
if self.tabuleiro[linha][col]:
possible[self.tabuleiro[linha][col]] = 0
#vertical check
for line in range(9):
if self.tabuleiro[line][coluna]:
possible[self.tabuleiro[line][coluna]] = 0
#mini square check
linhaSquare = (linha // 3) * 3
colunaSquare = (coluna // 3) * 3
for l in range(linhaSquare, linhaSquare + 3):
for c in range(colunaSquare, colunaSquare + 3):
if self.tabuleiro[l][c]:
possible[self.tabuleiro[l][c]] = 0
toTry = []
for k in range(1, 10):
if possible[k]:
toTry.append(k)
return toTry
def solve(self):
self.show()
print('')
if self.isFull():
for i in range(9):
for j in range(9):
self.solvedBoard[i][j] = self.tabuleiro[i][j]
self.gameRunning = False
self.tabuleiro = self.solvedBoard
elif self.gameRunning:
found = False
linha = 0
coluna = 0
for i in range(9):
for j in range(9):
if (not self.tabuleiro[i][j]):
linha = i
coluna = j
found = True
break
if found:
break
numbers = self.numberPossibilities(linha, coluna)
print(*numbers)
print('')
tamanho = len(numbers)
for k in range(tamanho):
if (not self.gameRunning):
self.tabuleiro = self.solvedBoard
break
self.tabuleiro[linha][coluna] = numbers[k]
self.solve()
if (self.gameRunning):
self.tabuleiro[linha][coluna] = 0
Note that the "show" function is only for debugging. I have an actual drawGrid function for handling the GUI.
My idea is to detect the first cell that needs to be changed, and, when the backtracking eventually comes back to It, with no other options to continue, It resets the board and then turns on a flag called "Impossible". Next iteration, the board detects that "Impossible" is on and resets the board, besides breaking the recursion.
However, that's seems too complicated, and I'm not sure how to do It without damaging code readability
What do you think? And also, Thanks in advance! This community is helping me a lot of this project :)

I want to return the sum of all indexes in n via recursion. How do I do this?

def final_sum(n):
n = str(n)
if int(n) == 0:
return 0
else:
x = int(n[0])
return x + int(final_sum(n[1:]))
print(final_sum(123))
For example, if my n is 123, I should be getting 6. But I am having an error in this code. Can anyone help? I have to use recursive function. So tell me what's wrong with the code.
in return x + int(final_sum(n[1:])), n[1:] is str type
in the beginning of the function, with n = str(n), you assume the input is an int
Besides, you did not consider the case that n[1:] can be empty in return x + int(final_sum(n[1:])).
Here is an anwser based on your code
def final_sum(n):
if n == 0:
return 0
n = str(n)
x = int(n[0])
if len(n)==1:
return x
else:
return x + final_sum(int(n[1:]))
Here is another version using % operation
def final_sum(n):
if n < 10:
return n
return n % 10 + final_sum(n // 10)
First of all, at the beggining I would do this instead of casting back and forth:
def final_sum(n):
if n<10:
return n
You see, the problem is, in the last recursive iteration, you are passing this to the function:
final_sum("")
When you should be passing an int. I think this is happening because your last cast is backwards and you never check how many digits the number has. So the code should look like this:
def final_sum(n):
if n<10:
return n
n = str(n)
x = int(n[0])
return x + final_sum(int(n[1:]))
print(final_sum(123))

Question about returning a value at the end of a recursive call

In the function fp, I am basically checking whether the difference between arguments of succesive recursive calls is less than a certain number and if it is so, I would like to return the last argument. Here is the code:
pX = []
for n in range(100):
pX.append(1/((n+1)*(n+2)))
def phi1(p):
def phi2(u):
sum = 0
for k in range(len(p)):
sum += p[k]*(u**k)
return sum
return phi2
def fp(pt):
temp = phi1(pX)(pt)
print(temp)
if(abs(pt-temp) > 0.01):
fp(temp)
else:
return temp
print(fp(0.1))
The output, without print(temp) is none, with print(temp) is:
0.5175535907956329
0.619369692490415
0.6561427816319753
0.6714277125785142
0.6781654579021761
None
Desired output is 0.678. May I know where I went wrong?
You aren't returning anything when your function recurses. Add a return to where fp is called inside fp:
def fp(pt):
temp = phi1(pX)(pt)
print(temp)
if(abs(pt-temp) > 0.01):
return fp(temp)
else:
return temp

Python: TypeError: 'int' object is not iterable

I'm tackling this following question:
Write a function is_fib(n) that returns True if n is a Fibonacci number, and False otherwise.
This is my code:
def is_fib(n):
def fib(x):
if x == 0:
return 0
elif x == 1:
return 1
else:
return fib(x-1) + fib(x-2)
for a in n:
if fib(a) == n:
result = True
break
else:
result = False
return result
Running this give rise to:
TypeError: 'int' object is not iterable.
I have been staring at the code for half an hour. Any help is greatly appreciated.
I think you mean
for a in range(n)
not
for a in n
As jozefg said you are missing range(n)
also notice that you need range(n+2) to cover all cases
def is_fib(n):
def fib(x):
if x == 0:
return 0
elif x == 1:
return 1
else:
return fib(x-1) + fib(x-2)
for a in range(n+2):
if fib(a) == n:
return True
return False
print(is_fib(3))
Firstly thanks to the two guys that helped me.
However, for Yoav's edition, python will run into an error when n is a really big number.
This is my new and improved version.
def is_fib(n):
if n < 0:
return False
else:
fib_0 = 0
fib_1 = 1
if n == fib_0 or n == fib_1:
return True
else:
for a in range(2,n+2):
fib = fib_0 + fib_1
fib_0,fib_1 = fib_1,fib
if fib >= n:
break
return fib == n

Resources