help reading code very short (fibonacci)

Anonymous
timer Asked: Nov 16th, 2013
account_balance_wallet $5

Question Description

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)


Tutor Answer

dagrawal
School: Duke University

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

flag Report DMCA
Review

Anonymous
awesome work thanks

Similar Questions
Hot Questions
Related Tags
Study Guides

Brown University





1271 Tutors

California Institute of Technology




2131 Tutors

Carnegie Mellon University




982 Tutors

Columbia University





1256 Tutors

Dartmouth University





2113 Tutors

Emory University





2279 Tutors

Harvard University





599 Tutors

Massachusetts Institute of Technology



2319 Tutors

New York University





1645 Tutors

Notre Dam University





1911 Tutors

Oklahoma University





2122 Tutors

Pennsylvania State University





932 Tutors

Princeton University





1211 Tutors

Stanford University





983 Tutors

University of California





1282 Tutors

Oxford University





123 Tutors

Yale University





2325 Tutors