help reading code very short (fibonacci)

label Programming
account_circle Unassigned
schedule 1 Day
account_balance_wallet $5

I would like someone to explain line by line what this is doing in python:


def fib(n):
    if n == 0:
        return 0
    elif n == 1:
        return 1
    else:
        return fib(n-1) + fib(n-2)


Nov 16th, 2013
Actually this is returning the nth element in the Fibonacci series using recursion.
Suppose number is 3, then the 3rd element would be 2

LINE 1: defines a function with name fib which is taking a number as parameter n=3
LINE 2-3: if number is zero then return 0. In our case it is not so next statement would be executed
LINE 4-5: else if number is 1 return 1. In our case it is not so next statement
LINE 5-6 else now we calling fib(3-1) + fib(3-2) = 1 + 1 = 2

fib(3-1) execution n=2
LINE 2: would return false goto LINE 4
LINE 4: woudl be false goto LINE 6
LINE 6 would be executed fib(2-1) + fib(2-2) = 1 + 0 = 1
fib(2-1) n=1
LINE 2: return false goto LINE 4
LINE 4: be true do return 1
fib(2-2) n=0
LINE 2: return 0

fib(3-2) n=1
LINE 2: return false goto LINE 4
LINE 4: true return 1
Nov 16th, 2013

Hello is possible to dis uss with u verbally? Maybe on skype?

Nov 16th, 2013

Did you know? You can earn $20 for every friend you invite to Studypool!
Click here to
Refer a Friend
...
Nov 16th, 2013
...
Nov 16th, 2013
Jun 23rd, 2017
check_circle
Mark as Final Answer
check_circle
Unmark as Final Answer
check_circle
Final Answer

Secure Information

Content will be erased after question is completed.

check_circle
Final Answer