Fibonacci with recursion in Python
Each Fibonacci number is the sum of the two before it, so a recursive function calls itself twice. That repeats the same work many times, and memoization fixes it by remembering every answer.
The arrow keys step through it. Edit the code to try your own input.
How it works
fib(n)returnsfib(n - 1) + fib(n - 2).fib(0)andfib(1)are the base cases.- Both calls split again, so the number of calls grows very fast as
ngrows. - The same values are worked out again and again:
fib(3)runs twice andfib(2)three times, 15 calls in all. fib_memosaves each answer in the dictionarymemo, so every value is worked out once and later calls just look it up: 9 calls instead of 15.- Plain recursion takes O(2ⁿ) time. With memoization it takes O(n).
What to watch
- Watch
callsin the global frame climb to 15 for the plain version. - Watch
fib(5)callfib(3)again, afterfib(4)has already worked it out once. - Watch
memofill up frommemo[2]upwards, and thenfib_memo(2, memo)andfib_memo(3, memo)return at once from the dictionary.
The code
calls = 0 def fib(n): global calls calls += 1 if n < 2: return n # fib(0) = 0, fib(1) = 1 return fib(n - 1) + fib(n - 2) def fib_memo(n, memo): if n in memo: return memo[n] # worked out before: just look it up if n < 2: return n memo[n] = fib_memo(n - 1, memo) + fib_memo(n - 2, memo) return memo[n] print("fib(5) =", fib(5), "after", calls, "calls") memo = {} print("fib_memo(5) =", fib_memo(5, memo), "memo:", memo)
Output
fib(5) = 5 after 15 calls
fib_memo(5) = 5 memo: {2: 1, 3: 2, 4: 3, 5: 5}Open it in the editor · Python Program to Print the Fibonacci Series Using Recursion, explained