Skip to content

Instantly share code, notes, and snippets.

@yashbhutoria
Created June 30, 2020 15:20
Show Gist options
  • Save yashbhutoria/e8082663a7aabfd12c18d9e175b4bf82 to your computer and use it in GitHub Desktop.
Save yashbhutoria/e8082663a7aabfd12c18d9e175b4bf82 to your computer and use it in GitHub Desktop.
A simple decorator to cache function calls with same arguments. Useful to optimize recursive functions with repeating calls.
# The decorator to cache function calls
def cached(func):
cache = dict()
def decorator(*args):
if tuple(args) not in cache:
cache[tuple(args)] = func(*args)
return cache[tuple(args)]
return decorator
# Usage example
@cached
def fib(n):
if n < 2:
return n
else:
return fib(n-1) + fib(n-2)
print([fib(x) for x in range(1000)])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment