How does return statement with recursion calls hold intermediate values in Python?

后端 未结 2 431
迷失自我
迷失自我 2021-01-15 08:42

Was reviewing some python code related to recursion calls and noticed the return statement looked interesting. How does the recursion work when there is no variable assignm

2条回答
  •  春和景丽
    2021-01-15 08:58

    The function returns the value to the call higher in the call stack, why do you think it needs a variable, e.g. take a simple recursive call:

    def r(n):
        if n == 0:
             return 0
        return 1 + r(n-1)
    

    Then the call stack would look like:

    r(3):
        return 1 + r(2)
        r(2):
            return 1 + r(1)
            r(1):
                return 1 + r(0)
                r(0):
                    return 0
    

    So when you unwind the call stack you get:

    r(3):
        return 1 + r(2)
        r(2):
            return 1 + r(1)
            r(1):
                return 1 + 0
    --
    r(3):
        return 1 + r(2)
        r(2):
            return 1 + 1
    --
    r(3):
        return 1 + 2
    --
    3
    

提交回复
热议问题