...
/Where to Use Dynamic Programming
Where to Use Dynamic Programming
In this lesson, we will learn about some problem characteristics in dynamic programming.
Dynamic programming, the magic wand
Do you remember the run time complexity of the Fibonacci algorithm from earlier lessons? We even saw how bad that algorithm performed as we tried to calculate a slightly higher (~50) Fibonacci number. We have modified that algorithm to remember the values it has already evaluated to avoid re-evaluations. Run this code with different values to see how much time the algorithm takes. For comparison, we have reproduced the simple recursion-based solution below as well as in the other tab.
import timeimport matplotlib.pyplot as pltcalculated = {}def fib(n):if n == 0: # base case 1return 0if n == 1: # base case 2return 1elif n in calculated:return calculated[n]else: # recursive stepcalculated[n] = fib(n-1) + fib(n-2)return calculated[n]showNumbers = Truenumbers = 20
Magical! Look at the almost linear time complexity curve formed now instead of an ...