[Python] Recursive functions memory usage

Discussão em 'Python' iniciado por Stack, Abril 23, 2025.

  1. Stack

    Stack Membro Participativo

    I have here a recursive function:

    def pow(x, n):
    if n == 0:
    return 1
    else:
    return x * pow(x, n-1)
    answer = pow(a, b)


    And an iterative:

    def pow(x, n): # n != 0
    answer = x
    while n > 1:
    answer *= x
    n -= 1
    return answer
    answer = pow(a, b)


    I'd like to know which one of the them use more memory. I think recursively uses more memory because it keeps 'variables' passed for each function call. If that's right, what would be an formalism to explain this? Is there a nice way to track this memory usage inside code?


    I don't think It's a duplicate. The main question isn't about track the memory usage, but It's about the recursive memory usage.

    Continue reading...

Compartilhe esta Página