Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def fibonacci(num):
- if num <= 2:
- return 1
- return fibonacci(num - 1) + fibonacci(num - 2)
- def exponential(base, exp):
- value = 1
- for i in range(exp):
- value *= base
- return value
- def caching(func):
- def wrapper(self, *args):
- page = (func.__name__, ) + args
- if page in self._Principle__cache.keys():
- print('cache hit')
- return self._Principle__cache[page]
- print('cache miss')
- self._Principle__cache[page] = func(self, *args)
- return self._Principle__cache[page]
- return wrapper
- class Principle(object):
- __slot__ = ['__cache']
- def __init__(self):
- self.__cache = {}
- @caching
- def fibonacci(self, num):
- return fibonacci(num)
- @caching
- def exponential(self, base, exp):
- return exponential(base, exp)
- p = Principle()
- print('fibonacci 35 =', p.fibonacci(35))
- print('fibonacci 35 =', p.fibonacci(35))
- print('2 exp 10 =', p.exponential(2, 10))
- print('2 exp 10 =', p.exponential(2, 10))
- print('cache = ', p._Principle__cache)
- '''result
- cache miss
- fibonacci 35 = 9227465
- cache hit
- fibonacci 35 = 9227465
- cache miss
- 2 exp 10 = 1024
- cache hit
- 2 exp 10 = 1024
- cache = {('fibonacci', 35): 9227465, ('exponential', 2, 10): 1024}
- '''
Add Comment
Please, Sign In to add comment