1. Learn
  2. /
  3. Courses
  4. /
  5. Data Structures and Algorithms in Python

Exercise

Fibonacci sequence

In this exercise, you will implement the Fibonacci sequence, which is ubiquitous in nature. The sequence looks like this: "0, 1, 1, 2, 3, 5, 8…". You will create a recursive implementation of an algorithm that generates the sequence.

The first numbers are 0 and 1, and the rest are the sum of the two preceding numbers.

We can define this sequence recursively as: \(fib(n)=fib(n-1)+fib(n-2)\), with \(fib(0)=0\) and \(fib(1)=1\), being \(n\) the \(nth\) position in the sequence.

In the first step, you will code Fibonacci using recursion. In the second step, you will improve it by using dynamic programming, saving the solutions of the subproblems in the cache variable.

Instructions 1/2

undefined XP
  • 1
    • Define the base case.
    • Call the fibonacci() function recursively.
  • 2
    • Check if the value exists in cache.
    • Save the result in cache to avoid recalculating it later.