#๐Ÿ”’ help with recursive function

15 messages ยท Page 1 of 1 (latest)

tall vaultBOT
#

@safe rapids

Python help channel opened

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.

placid quest
#

!code

tall vaultBOT
#
Formatting code on Discord

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

For long code samples, you can use our pastebin.

safe rapids
#

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")
placid quest
safe rapids
#

if you'd like the remaining code for context, please let me know

safe rapids
placid quest
safe rapids
#

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

placid quest
#

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.

safe rapids
#

got it, you cleared up a really foggy part of this code for me, i really appreciate your help

#

!close

tall vaultBOT
#
Python help channel closed

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.