-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmemoization.py
82 lines (58 loc) · 1.45 KB
/
memoization.py
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#!/usr/bin/env python
'''
memoization.py - Transparent memoization using decorators.
Author: Eric Saunders
January 2011
'''
class Memoize(object):
def __init__(self, func):
self.func = func
self.cache = {}
def __call__(self, *args):
print "Args:", args
if not args in self.cache:
print "...not found..."
answer = self.func(*args)
print "Added", answer, "to cache..."
self.cache[args] = answer
return self.cache[args]
def __repr__(self):
"""Return the function's docstring."""
return self.func.__doc__
class SimpleDecorator(object):
def __init__(self, f):
print "Inside SimpleDecorator constructor."
self.f = f
def __call__(self):
print "Inside SimpleDecorator call"
self.f()
print "Finished executing function"
@Memoize
def fibonacci(n):
if n in (0, 1):
return n
return fibonacci(n-1) + fibonacci(n-2)
def decorate(f):
def decorated():
print "Decorating..."
f()
print "Finished decorating."
return decorated
indent = " "
#@decorate
def hello_world():
global indent
print "Hello, world!"
print indent, "blah"
indent = " "
#recurse
indent = " "
#f = Memoize(fibonacci)
#g = SimpleDecorator(hello_world)
#h = decorate(hello_world)
print fibonacci(10)
print fibonacci(110)
#print f(12)
#g()
#h()
#hello_world()