Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python global variables in recursion get different result

I have this code, which prints 1:

s = 0

def dfs(n):
    global s
    if n > 10:
        return 0
    s += dfs(n + 1)
    return n

dfs(0)
print(s)

If I modify dfs like this:

def dfs(n):
    global s
    if n > 10:
        return 0
    i = dfs(n + 1)
    s += i
    return n

it will print 55

I know what is a better way to write the dfs. I just want to know why the value of s is different after the call of two dfs

like image 261
ValueError Avatar asked Oct 22 '25 05:10

ValueError


2 Answers

Python is interpreted and executed from top to bottom, so in the first version you have:

s += dfs(n + 1)

which is exact as:

s = s + dfs(n + 1)

So when you do this recursively you have on stack these commands:

s = 0 + dfs(1) # <-- dfs(1) will return 1
s = 0 + dfs(2) # <-- dfs(2) will return 2
...
s = 0 + dfs(9) # <-- dfs(9) will return 9
s = 0 + dfs(10) # <-- dfs(10) will return 10
s = 0 + dfs(11) # <-- dfs(11) will return 0

So when you observe, the last step is s = 0 + 1 and you see the 1 as final result.


The second version

i = dfs(n + 1)
s += i

You assign to s after dfs(n + 1) is evaluated so you see the final answer 55


NOTE: If you rewrite the first version s += dfs(n + 1) to s = dfs(n + 1) + s you will see the result 55 too.

like image 125
Andrej Kesely Avatar answered Oct 23 '25 17:10

Andrej Kesely


When you call it like this:

s += dfs(n + 1)

The initial value of s before the increment is taken before it has been modified in the recursive call, so the assignment ends up overwriting whatever change was made in the recursive call.

But when you call it like this:

i = dfs(n + 1)
s += i

The initial value of s is taken after it has been modified in the recursive call, so the change in the recursive call is preserved.

In general, recursive functions don't play well with global variables. Recursive functions need their own separate context.

like image 23
John Gordon Avatar answered Oct 23 '25 19:10

John Gordon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!