DEV Community

Discussion on: Recursion in Python(A Gentle Introduction)

Collapse
 
jaakofalltrade profile image
Jaako • Edited

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:

def fibonacci(n):
    if n == 1:
        return 1
    elif n == 2:
        return 1
    elif n > 2:
        return fibonacci(n-1) + fibonacci(n-2)

You add memoization to optimize the recursion:

fibonacci_cache = {}

def fibonacci(n):
    # If we have cached the value, then return it
    if n in fibonacci_cache:
         return fibonacci_cache[n]

    # Compute the Nth term
    if n == 1:
        return 1
    elif n == 2:
        return 1
    elif n > 2:
        return fibonacci(n-1) + fibonacci(n-2)

    # Cache the value and return it
    fibonacci_cache[n] = value
    return value

Or you can also use a builtin python tool:

from functools import lru_cache

@lru_cache(maxsize = 1000)
def fibonacci(n):
    if n == 1:
        return 1
    elif n == 2:
        return 1
    elif n > 2:
        return fibonacci(n-1) + fibonacci(n-2)

Here is the complete video explaining it clearly, plus it is where I got this code from.