1

I was wondering if the 2 recursive functions below have different memory complexities:

1

def f(x):
    if x == 100:
        return 1
    return 1 + f(x + 1)
res = f(1) 
res # evaluates to 100

2

res = 1
def g(x):
    global res
    if x == 100:
        return
    res += 1
    g(x + 1)
g(1)
res # also evaluates to 100

From my understanding, it appears that since f's recursive calls are being returned, Python must keep all 100 function calls in the stack frame until x reaches 100. On the other hand, g's recursive calls are not returned, which means that the stack frame only needs to keep 1 function call at any given time. Therefore, f has linear memory complexity while g has constant. Is my understanding correct? Thanks!

19e9030393
  • 23
  • 1
  • 5
  • 1
    Your understanding would be correct if Python optimized tail recursion. This is called "TCO" (tail call optimization). The latter form of recursion would be called *tail recursion*, since the recursive call is the last instruction of the function. Some languages (e.g. Lua) require `return tail_call(...)` for tail recursion to work. – Luatic Jul 12 '22 at 10:11

0 Answers0