Memoization is the storing of results for future use. Python's functools module includes a simple decorator, lru_cache
, that handles this for you. So for your example:
@lru_cache(maxsize=None)
def factorial( n ):
...
will store each result of factorial, including its recursive calls. That means the next time you call factorial you will not perform the full calculation, but instead stop as soon as you reach a call that has been called before. At that point the result will be pulled from the previously stored results.
These answers might also be useful to you: What is memoization and how can I use it in Python?