JamCoders

💾 Download

Week 2 - Day 2, Lecture 2

Recursion

Exercise

The Fibonacci sequence is 1, 1, 2, 3, 5, 8 etc. The nth Fibonacci number F(n) where n > 2 can be found using F(n) = F(n-2) + F(n-1)

Remember that F(1) = 1 and F(2) = 1

Complete the function Fib to find the 28th Fibonacci number (n = 28)
In [1]:
def fib(n):
    if n <= 1:
        return n
    else:
        return fib(n-1)+fib(n-2)
In [6]:
fib(28)
Out[6]:
317811
In [28]:
def check(f,v):
    if f==v:
        print(f"Congratulations! {f} has passed the test case")
In [29]:
# TEST_CASE
check(fib(28), 317811)
Congratulations! 317811 has passed the test case