-1

I was playing with a sudoku solver, and came across this interesting behavior. When I enter a number (0,5) the function will keep going up to the upper limit (5). Once the limit is reached it still keeps printing my number (a), but decreasing the value? (Shown below).

Why is this?

def solver(a):
    print("->",a)
    if a == 0 or a == 5:
        return
    else:
        a = a+1
        print("-->",a)
        solver(a)
    print("---")
    print(a)

gives

-> 2
--> 3
-> 3
--> 4
-> 4
--> 5
-> 5
---
5
---
4
---
3
  • 1
    It is just executing the part of the function that comes after returning from the recursed function call. – mkrieger1 Jun 26 '20 at 22:08
  • 1
    Does this answer your question? [Understanding how recursive functions work](https://stackoverflow.com/questions/25676961/understanding-how-recursive-functions-work) – mkrieger1 Jun 26 '20 at 22:10
  • Thanks! but why the decrement of the value (a)? – Christian Sutton Jun 26 '20 at 22:10
  • 1
    Because `solver(5)` was called from `solver(4)`, and after returning from `solver(5)`, `solver(4)` continues. And since `solver(4)` was called from `solver(3)`, after `solver(4)` returns, the rest of `solver(3)` is executed, etc. – mkrieger1 Jun 26 '20 at 22:12
  • Nailed it. That is so clear. Thank you so much! – Christian Sutton Jun 26 '20 at 22:16

1 Answers1

1

This may help you to see what is going on: I've added a variable recursionLevel so that you can see at what level in the recursion the numbers are printed.

def solver(a, recursionLevel):
    print("->",a, recursionLevel)
    if a == 0 or a == 5:
        return
    else:
        a = a+1
        print("-->",a, recursionLevel)
        solver(a, recursionLevel + 1)
    print("---")
    print(a, recursionLevel)
    

solver(2, 0)

This gives:

-> 2 0
--> 3 0
-> 3 1
--> 4 1
-> 4 2
--> 5 2
-> 5 3
---
5 2
---
4 1
---
3 0

As you can see, the lower numbers are from the shallower recursion levels that continue their execution after the recursive call returns. The higher values are local to those deeper calls and do not affect the value in the caller.

alani
  • 12,573
  • 2
  • 13
  • 23