Advertisement
Guest User

Untitled

a guest
Jul 7th, 2015
221
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.54 KB | None | 0 0
  1. class Memoize(object):
  2.  
  3. def __init__(self, f):
  4. self.f = f
  5. self.computed = {}
  6.  
  7. def __call__(self, *args):
  8. xs = self.computed.get(args)
  9. if xs :
  10. return xs
  11. else :
  12. value = self.f(*args)
  13. self.computed[args] = value
  14. return value
  15.  
  16. def unmemoize(self):
  17. return self.f
  18.  
  19.  
  20. def fact(n):
  21. print("computing", n)
  22. if n == 0:
  23. return 1
  24. else:
  25. return fact(n-1) * n
  26.  
  27. fact = Memoize(fact)
  28.  
  29. # fact(5)
  30. # fact(6)
  31. # ...
  32.  
  33. fact = fact.unmemoize()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement