Created
December 9, 2015 09:16
-
-
Save Greenheart/2d47886011d58b3385f8 to your computer and use it in GitHub Desktop.
A decorator that works as a simple cache
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
from math import sqrt | |
def cache(F): | |
"""A simple cache decorator""" | |
cache = dict() | |
def wrapper(*args): | |
try: | |
return cache[args] | |
except KeyError: | |
# Result not in cache --> Calculate and store it | |
result = F(*args) | |
cache[args] = result | |
return result | |
return wrapper | |
@cache | |
def is_prime(x): | |
"""Non-accurate implementation of prime check""" | |
iterations = 0 | |
for i in range(2, int(sqrt(x)) + 1): | |
iterations += 1 | |
if i % x == 0: | |
return False | |
print('{} iterations'.format(iterations)) | |
return True |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment