Skip to content

Instantly share code, notes, and snippets.

@singhAmandeep007
Last active April 25, 2024 12:38
Show Gist options
  • Select an option

  • Save singhAmandeep007/c3276802a48be64faf8a2a0f71f7af3b to your computer and use it in GitHub Desktop.

Select an option

Save singhAmandeep007/c3276802a48be64faf8a2a0f71f7af3b to your computer and use it in GitHub Desktop.
Caching fibonacci function using decorators in python
def count_calls(func):
"""
This function is a decorator that keeps track of the number of times a function is called.
It takes a function as input and returns a new function that behaves exactly like the input function,
but also increments a counter and prints the number of calls each time the function is called.
:param func: The function to be decorated.
:return: The decorated function that counts and prints the number of calls.
"""
@functools.wraps(func)
def wrapper_count_calls(*args, **kwargs):
wrapper_count_calls.num_calls += 1 # track no. of calls
# !r is for __repr__ representation
print(f"Call {wrapper_count_calls.num_calls} of {func.__name__!r}")
return func(*args, **kwargs)
wrapper_count_calls.num_calls = 0
return wrapper_count_calls
def cache(func):
"""Keep a cache of previous function calls"""
@functools.wraps(func)
def wrapper_cache(*args, **kwargs):
cache_key = args + tuple(kwargs.items())
if cache_key not in wrapper_cache.cache:
wrapper_cache.cache[cache_key] = func(*args, **kwargs)
return wrapper_cache.cache[cache_key]
wrapper_cache.cache = {}
return wrapper_cache
@cache
@count_calls
def fibonacci(num):
if num < 2:
return num
return fibonacci(num - 1) + fibonacci(num - 2)
fibonacci(5) # only 6 calls
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment