PY
py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
"""Memoization Demo
This is a technique to store in memory the
function return values, if it had been run
already with specific parameters.
"""
from functools import lru_cache, wraps
from time import time
def timeit(func):
"""Decorator to measure time"""
@wraps(func)
def wrapper(*args, **kwargs):
t = time()
result = func(*args, **kwargs)
t = (time() - t) * 1000
print(f'{func.__doc__}{args}: {t:.6f} ms')
return result
return wrapper
@timeit
def fact(n: int) -> int:
"""Recursive factorial"""
return 1 if n <= 1 else n * fact(n - 1)
@lru_cache(maxsize=2)
@timeit
def mem_fact(n: int) -> int:
"""Memoized factorial"""
Enter to Rename, Shift+Enter to Preview
OUTPUT
Run