Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (50.2k points)
I just a newbie in Python and I am not having any idea what memoization is and where to use it. Kindly explain in layman's terms...

1 Answer

0 votes
by (108k points)
edited by

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:

Related questions

0 votes
1 answer
asked Jan 13, 2021 in Python by ashely (50.2k points)
0 votes
1 answer
asked Sep 26, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer

Browse Categories

...