Created
September 5, 2020 10:09
-
-
Save raeq/a80a3717399d5cc0edd00861fbc61b16 to your computer and use it in GitHub Desktop.
Memoized recursion
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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