June 2019
Beginner to intermediate
770 pages
19h 24m
English
The idea behind memoization is to cache previous results to avoid recomputing them. We'll use considerably more memory, but we can also dramatically speed up performance by avoiding computation.
An ordinary function doesn't have a place to cache previous results. A function is not expected to be stateful. A callable object, however, can be stateful. It can include a cache of previous results.
The following is a memoized version of our Power callable object:
class Power5: def __init__(self): self.memo = {} def __call__(self, x: int, n: int) -> int: if (x, n) not in self.memo: if n == 0: self.memo[x, n] = 1 elif n % 2 == 1: self.memo[x, n] = self.__call__(x, n-1) * x elif n % 2 == 0: t = self.__call__(x, n //
Read now
Unlock full access