Cool post-Elijah!, Memoization works great for recursion! Although it kinda sounds like Tweety bird pronouncing memorization the same way he pronounces "I thought I thaw a putty cat". Nevertheless here is how you can implement it in Python.
Instead of doing this which consumes a lot of memory:
fibonacci_cache={}deffibonacci(n):# If we have cached the value, then return it
ifninfibonacci_cache:returnfibonacci_cache[n]# Compute the Nth term
ifn==1:return1elifn==2:return1elifn>2:returnfibonacci(n-1)+fibonacci(n-2)# Cache the value and return it
fibonacci_cache[n]=valuereturnvalue
Cool post-Elijah!, Memoization works great for recursion! Although it kinda sounds like Tweety bird pronouncing memorization the same way he pronounces "I thought I thaw a putty cat". Nevertheless here is how you can implement it in Python.
Instead of doing this which consumes a lot of memory:
You add memoization to optimize the recursion:
Or you can also use a builtin python tool:
Here is the complete video explaining it clearly, plus it is where I got this code from.