Python global variables in recursion get different result

67 Views Asked by At

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

2

There are 2 best solutions below

0
Andrej Kesely On BEST ANSWER

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.

0
John Gordon On

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.