Guest User

Untitled

a guest
Nov 18th, 2017
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.24 KB | None | 0 0
  1. def fibonacci(num):
  2. if num <= 2:
  3. return 1
  4. return fibonacci(num - 1) + fibonacci(num - 2)
  5.  
  6. def exponential(base, exp):
  7. value = 1
  8. for i in range(exp):
  9. value *= base
  10. return value
  11.  
  12. def caching(func):
  13. def wrapper(self, *args):
  14. page = (func.__name__, ) + args
  15. if page in self._Principle__cache.keys():
  16. print('cache hit')
  17. return self._Principle__cache[page]
  18. print('cache miss')
  19. self._Principle__cache[page] = func(self, *args)
  20. return self._Principle__cache[page]
  21. return wrapper
  22.  
  23. class Principle(object):
  24. __slot__ = ['__cache']
  25.  
  26. def __init__(self):
  27. self.__cache = {}
  28.  
  29. @caching
  30. def fibonacci(self, num):
  31. return fibonacci(num)
  32.  
  33. @caching
  34. def exponential(self, base, exp):
  35. return exponential(base, exp)
  36.  
  37. p = Principle()
  38. print('fibonacci 35 =', p.fibonacci(35))
  39. print('fibonacci 35 =', p.fibonacci(35))
  40. print('2 exp 10 =', p.exponential(2, 10))
  41. print('2 exp 10 =', p.exponential(2, 10))
  42. print('cache = ', p._Principle__cache)
  43.  
  44. '''result
  45. cache miss
  46. fibonacci 35 = 9227465
  47. cache hit
  48. fibonacci 35 = 9227465
  49. cache miss
  50. 2 exp 10 = 1024
  51. cache hit
  52. 2 exp 10 = 1024
  53. cache = {('fibonacci', 35): 9227465, ('exponential', 2, 10): 1024}
  54. '''
Add Comment
Please, Sign In to add comment