Last active
November 16, 2017 09:03
-
-
Save nulledge/925f346a09519808635ef9608d3e23de to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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} | |
''' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment