Recursion function in Python

后端 未结 10 2158
庸人自扰
庸人自扰 2020-12-15 11:52

Consider this basic recursion in Python:

def fibonacci(number):
    if number == 0: return 0
    elif number == 1:
        return 1
    else:
        return          


        
10条回答
  •  隐瞒了意图╮
    2020-12-15 12:20

    You can figure this out yourself, by putting a print function in the function, and adding a depth so we can print it out prettier:

    def fibonacci(number, depth = 0):
        print " " * depth, number
        if number == 0:
            return 0
        elif number == 1:
            return 1
        else:
            return fibonacci(number-1, depth + 1) + fibonacci(number-2, depth + 1)
    

    Calling fibonacci(5) gives us:

    5
     4
      3
       2
        1
        0
       1
      2
       1
       0
     3
      2
       1
       0
      1
    

    We can see that 5 calls 4, which goes to completion, and then it calls 3, which then goes to completion.

提交回复
热议问题