-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmemoize.py
More file actions
executable file
·28 lines (26 loc) · 862 Bytes
/
memoize.py
File metadata and controls
executable file
·28 lines (26 loc) · 862 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
class memoize(object):
"""
Decorator that caches a function's return value each time it is called.
If called later with the same arguments, the cached value is returned,
and not re-evaluated
"""
def __init__(self, func):
self.func = func
self.cache = {}
def __call__(self, *args):
try:
return self.cache[args]
except KeyError:
self.cache[args] = value = self.func(*args)
return value
except TypeError:
# uncachable -- for instance, passing a list as an argument
return self.func(*args)
def __repr__(self):
"Return the function's docstring."
return self.func.__doc__
def fibonacci(n):
"Return the nth fibonacci number"
if n in (0,1):
return n
return fibonacci(n-1) + fibonacci(n-2)