-
-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy path5-memoize-file.py
More file actions
34 lines (29 loc) · 740 Bytes
/
Copy path5-memoize-file.py
File metadata and controls
34 lines (29 loc) · 740 Bytes
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
30
31
32
33
34
import os, pickle
from functools import wraps
def memoize(fn):
if os.path.exists('memoize.pkl'):
print('Reading cache file!')
with open('memoize.pkl') as f:
cache = pickle.load(f)
else:
cache = {}
@wraps(fn)
def wrap(*args):
if args not in cache:
print('Running function with argument', args[0])
cache[args] = fn(*args)
# update the cache file
with open('memoize.pkl', 'wb') as f:
pickle.dump(cache, f)
else:
print('Result in cache!')
return cache[args]
return wrap
@memoize
def sqrt(x):
return x**2
print(sqrt(5))
print(sqrt(5))
print(sqrt(7))
print(sqrt(5))
print(sqrt(7))