Created
June 30, 2020 15:20
-
-
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.
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
# 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