Skip to content

Instantly share code, notes, and snippets.

@Greenheart
Created December 9, 2015 09:16
Show Gist options
  • Save Greenheart/2d47886011d58b3385f8 to your computer and use it in GitHub Desktop.
Save Greenheart/2d47886011d58b3385f8 to your computer and use it in GitHub Desktop.
A decorator that works as a simple cache
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