Recursion function in Python

后端 未结 10 2135
庸人自扰
庸人自扰 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:30

    Matthew and MArtjin are right but I thought I might elaborate:

    Python does stuff from left to right whenever it can. Exceptions to this rule are implied by brackets.

    in x*power(x, y-1): x is evaluated then power is evaluated

    While in fibonacci(number-1) + fibonacci(number-2), fibonacci(number-1) is evaluated (recursively, til it stops) and then fibonacci(number-1) is evaluated

    0 讨论(0)
  • 2020-12-15 12:32
    def fib(n):
      if n <= 1:
      return n
    else :
      return fib(n - 1) + fib(n - 2)
    
    0 讨论(0)
  • 2020-12-15 12:38

    Your second recursion functions does this (example), so 1 will not be returned.

    power(2, 3)
    
    2 * power(2, 2)
    
    2 * 2 * power(1,2)
    
    2 * 2 * 2 * power(0,2) # Reaching base case
    
    2 * 2 * 2 * 1
    
    8
    
    0 讨论(0)
  • 2020-12-15 12:40

    In the expression fibonacci(number-1) + fibonacci(number-2) the first function call will have to complete before the second function call is invoked.

    So, the whole recursion stack for the first call has to be complete before the second call is started.

    0 讨论(0)
提交回复
热议问题