Journey to Master Python (WIP)
Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
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
29
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()}')
Enter to Rename, Shift+Enter to Preview
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content