Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursion on Fibonacci Sequence

I need some help in understanding the processing that happens here, so let´s say I call fib(5) I want the fibonacci 5, which is 8. But my brain in trying to understand the algorithm says it´s not. This is how i (wrongly) think:

return fib(4) + fib(3) // Stack frame 1
return fib(3) + fib(1) // Stack frame 2

now cause x is 1 fib(1), the conditional statement if x == 0 or x == 1: causes the recursion to end. Which according to my logic would become 3+1+4+3. Please correct my faulty logic.

def fib(x):
    """assumes x an int >= 0
       returns Fibonacci of x"""
    assert type(x) == int and x >= 0
    if x == 0 or x == 1:
        return 1
    else:
        return fib(x-1) + fib(x-2)
like image 717
Tom Lilletveit Avatar asked Dec 01 '12 10:12

Tom Lilletveit


2 Answers

Here is the full expansion of what happens:

fib(5) expands to fib(4)+fib(3)
  fib(4) expands to fib(3)+fib(2)
    fib(3) expands to fib(2)+fib(1)
      fib(2) expands to fib(1)+fib(0)
        fib(1) evaluates to 1
        fib(0) evaluates to 1
      fib(1) evaluates to 1
    fib(2) expands to fib(1)+fib(0)
      fib(1) evaluates to 1
      fib(0) evaluates to 1
  fib(3) expands to fib(2)+fib(1)
    fib(2) expands to fib(1)+fib(0)
      fib(1) evaluates to 1
      fib(0) evaluates to 1
    fib(1) evaluates to 1

If you count the ones, you get 8 as the answer.

like image 121
NPE Avatar answered Oct 19 '22 22:10

NPE


For all x greater than 1, the fib function calls itself twice:

  1. fib(5) becomes fib(4) + fib(3)
  2. and expands to (fib(3) + fib(2)) + (fib(2) + fib(1))
  3. and expands to ((fib(2) + fib(1)) + (fib(1) + fib(0))) + ((fib(1) + fib(0)) + 1)
  4. expands to (((fib(1) + fib(0)) + 1) + (1 + 1)) + ((1 + 1) + 1)
  5. expands to (((1 + 1) + 1) + (1 + 1)) + ((1 + 1) + 1)

which sums up to 8.

like image 31
Martijn Pieters Avatar answered Oct 20 '22 00:10

Martijn Pieters