Kindly be informed that Memoization is used to identify the outputs of function calls based on the function inputs and then returning the identified result rather than calculating the result again. You can compare this with a cache for function results.
Kindly refer to the below example for reference:
The below code is calculating the factorials using memoization way in Python:
factorial_memo = {}
def factorial(k):
if k < 2: return 1
if k not in factorial_memo:
factorial_memo[k] = k * factorial(k-1)
return factorial_memo[k]
The encapsulation is done on the memorization method into the below class:
class Memoize:You will get twisted and encapsulate the memorization method into the below class:
def __init__(self, f):
self.f = f
self.memo = {}
def __call__(self, *args):
if not args in self.memo:
self.memo[args] = self.f(*args)
#Warning: You may wish to do a deepcopy here if returning objects
return self.memo[args]
Then:
def factorial(k):
if k < 2: return 1
return k * factorial(k - 1)
factorial = Memoize(factorial)
For more information regarding the python basics, do refer to the below python tutorial video that will help you out in a better way: