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
Python is interpreted and executed from top to bottom, so in the first version you have:
which is exact as:
So when you do this recursively you have on stack these commands:
So when you observe, the last step is
s = 0 + 1and you see the1as final result.The second version
You assign to
safterdfs(n + 1)is evaluated so you see the final answer55NOTE: If you rewrite the first version
s += dfs(n + 1)tos = dfs(n + 1) + syou will see the result55too.