Skip to content

Instantly share code, notes, and snippets.

@hughdbrown
Last active February 27, 2024 17:36
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save hughdbrown/bf5c63792d5f912a162bf012fb6b4527 to your computer and use it in GitHub Desktop.
Save hughdbrown/bf5c63792d5f912a162bf012fb6b4527 to your computer and use it in GitHub Desktop.
Minimal lru_cache implementation for python 2.7
from functools import wraps
try:
from functools import lru_cache
except ImportError:
def lru_cache(user_function):
cache = {}
@wraps(user_function)
def wrapper(*args):
key = tuple(args)
if key not in cache:
cache[key] = user_function(*args)
return cache[key]
return wrapper
def fib(n):
if n in (1, 2):
return 1
else:
return fib(n - 2) + fib(n - 1)
@lru_cache
def fib2(n):
if n in (1, 2):
return 1
else:
return fib2(n - 2) + fib2(n - 1)
from datetime import datetime
def time_fn(fn, *args):
s = datetime.now()
print(fn(*args))
e = datetime.now()
print(e - s)
time_fn(fib, 40)
time_fn(fib2, 40)
@root-96
Copy link

root-96 commented Feb 27, 2024

thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment