#๐ help with recursive function
15 messages ยท Page 1 of 1 (latest)
@safe rapids
Remember to:
- Ask your Python question, not if you can ask or if there's an expert who can help.
- Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
- Explain what you expect to happen and what actually happens.
:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.
!code
i have the following snippet from my sudoku solving algorithm using backtracking in python. i understand the premises of how it works, and according to my code, it should return False the second the backtracking fails and reaches aa dead end. however, the code instead persists and continues until it returns the right answer. i am happy it does so, but i am not sure why. here is the code:
def solve():
for y1 in range(9):
for x1 in range(9):
if board[y1][x1] != 0: continue
for N1 in range(1, 10):
if move_allowed(N1, x1, y1):
board[y1][x1] = N1
if solve(): return True
board[y1][x1] = 0
# Tried all possible in empty pos. None worked; messed up before
return False
return True
if solve():
print(board)
else:
print("NO SOL")
Are you expecting return False to end all recursive calls?
if you'd like the remaining code for context, please let me know
yes, i think so because it continues till the dead end, at which it returns False, which should end the solve() entirely. however, it does not do this.
Yes. Note that recursion is not special. If function a calls function b, and b executes return False, does that cause a to also return?
ohh so the return False is in context of the if solve(): return True. since that outputs false, it goes back to the outside if move_allowed... statement which continues to replace board[y1][x1] = 0 because N1 does not satisfy it
When you return from a recursive call, that returns from that one call, and execution returns to the previous recursive call that made the recursive call that was returned from. If that makes sense.
Just like with all functions, when you return, execution picks up where it left off in the function that made the call. It doesn't matter if that was a recursive call or a "normal" function call.
got it, you cleared up a really foggy part of this code for me, i really appreciate your help
!close
This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.