Classic algorithms · 15 / 22 Exercise Medium

Fibonacci with memory

Objective

Create a Python program that computes the Fibonacci number n with recursion and a memory (dictionary) that avoids repeating calculations.

Instructions

  • Read an integer n between 0 and 50.
  • Define a recursive function fib(n) with fib(0) = 0 and fib(1) = 1. Before computing, check whether n is already in the memory dictionary; if not, compute it, store it and return it.
  • Use a global variable to count every call to fib (all of them, including those solved with the memory).
  • Show Fibonacci: X on the first line and Calls: K on the second.
Input
10
Output
Fibonacci: 55
Calls: 19

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise