pythonrecursionglobal

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


Solution

  • 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.