forked from UWPCE-PythonCert/IntroPython2016a
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmemoize.py
More file actions
38 lines (30 loc) · 917 Bytes
/
memoize.py
File metadata and controls
38 lines (30 loc) · 917 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
35
36
37
38
class Memoize:
"""
memoize decorator from avinash.vora
http://avinashv.net/2008/04/python-decorators-syntactic-sugar/
"""
def __init__(self, function): # runs when memoize class is called
self.function = function
self.memoized = {}
def __call__(self, *args): # runs when memoize instance is called
try:
return self.memoized[args]
except KeyError:
self.memoized[args] = self.function(*args)
return self.memoized[args]
@Memoize
def sum2x(n):
return sum(2 * i for i in range(n))
import time
def timed_func(func):
def timed(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
elapsed = time.time() - start
print("time expired: {}".format(elapsed))
return result
return timed
@timed_func
@Memoize
def sum2x(n):
return sum(2 * i for i in range(n))