usr bin env python def memoize function cached def wrapper if not in c

 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
#!/usr/bin/env python
def memoize(function, cached={}):
def wrapper(x, y):
if (x, y) not in cached:
cached[(x, y)] = function(x, y)
return cached[(x, y)]
return wrapper
class Memoization(object):
def __init__(self, function):
self.function = function
self.cached = {}
def __call__(self, x, y):
if (x, y) not in self.cached:
self.cached[(x, y)] = self.function(x, y)
return self.cached[(x, y)]
@memoize
def add(a, b):
print "%s + %s" % (a, b)
return a + b
@Memoization
def rem(c, d):
print "%s - %s" % (c, d)
return c - d
print add(1, 3)
print add(1, 4)
print add(1, 3)
print rem(1, 3)
print rem(1, 4)
print rem(1, 3)