Journey to Master Python (WIP)

ageekymonk
2,794 views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

Functools module

Memoization

Functools module supports memoization through lru_cache decorator. This way you dont need to write memoization code.

In the example adding the decorator @lru_cache does the needful. You can also see the cache details with cache_info

lru_cache Decorator
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
import time
from functools import lru_cache
def fibonacci(n):
if n < 2:
return n
return fibonacci(n-1) + fibonacci(n-2)
@lru_cache(maxsize=128)
def fibonacci_cached(n):
if n < 2:
return n
return fibonacci_cached(n-1) + fibonacci_cached(n-2)
time1 = time.time()
print(f'35 Fibonocci number is {fibonacci(35)}')
time2 = time.time()
print(f'Total time taken is {(time2-time1)*1000}ms')
time1 = time.time()
print(f'35 Fibonocci number is {fibonacci_cached(35)}')
time2 = time.time()
print(f'Total time taken is {(time2-time1)*1000 }ms')
print(f'{fibonacci_cached.cache_info()}')
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content