Skip to content

Instantly share code, notes, and snippets.

@raeq
Created September 5, 2020 10:09
Show Gist options
  • Save raeq/a80a3717399d5cc0edd00861fbc61b16 to your computer and use it in GitHub Desktop.
Save raeq/a80a3717399d5cc0edd00861fbc61b16 to your computer and use it in GitHub Desktop.
Memoized recursion
@memo
def fibonacci_wrapped(i: int = None) -> int:
"""
This technique uses exactly the same recursive algorithm as in the naive solution.
However, we are now using a technique known as "memoization". This is really useful in some
recursive algorithms, because otherwise the same set of values is constantly being calculated.
Here we use a nice and simple decorator to add the memoization capability.
However, we're still using recursion, and at some point the maximum recursion depth will be reached.
The technique of memoization is pretty sweet! We can memoize an existing recursive function to make
it perform much better.
>>> fibonacci_wrapped(80)
23416728348467685
>>> fibonacci_wrapped(100000)
Traceback (most recent call last):
...
RecursionError: maximum recursion depth exceeded in comparison
"""
if i == 0:
return 0
if i == 1:
return 1
return int(fibonacci_wrapped(i - 1) + fibonacci_wrapped(i - 2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment