Created
September 11, 2023 16:28
-
-
Save Veticus/1273644cd1563013534759a0982a0469 to your computer and use it in GitHub Desktop.
Memoisation demo in python
This file contains hidden or 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
# This is the memoization demo. | |
# First a wrapper is created, which can be used for each call of the fibonacci function. | |
# The wrapper will save (or cache) the result of each function call - index for a given set of arguments and keyword arguments. | |
from functools import wraps | |
from time import perf_counter | |
def memoize(func): # The memoisation needs to take a function, since it's a decorator. | |
cache = {} | |
@wraps(func) | |
def wrapper(*args, **kwargs): # Needs the arguments and keyword arguments - see info about making custom decorators. | |
key = str(args) + str(kwargs) # To make the result identifiable from its arguments - we want to store the results by the arguments given. | |
if key not in cache: # Add to cache, if it's not already in there. | |
cache[key] = func(*args, **kwargs) | |
return cache[key] | |
return wrapper | |
@memoize | |
def memoized_fibo(n) -> int: # This is the function that uses the memoisation. | |
if n < 2: | |
return n | |
return memoized_fibo(n - 1) + memoized_fibo(n - 2) | |
def non_memoized_fibo(n) -> int: # This is the function that doesn't use the memoisation. | |
if n < 2: | |
return n | |
return non_memoized_fibo(n - 1) + non_memoized_fibo(n - 2) | |
if __name__ == '__main__': | |
n = 35 # We'll try to calculate the n'th fibonacci number | |
print(f"Will try to find the {n}'th Fibonacci number.") | |
# This is the memoized run | |
start = perf_counter() | |
print(f"Result, memoized:\t\t\t{memoized_fibo(n)}") | |
end = perf_counter() | |
print(f"Duration, memoized:\t\t\t{end - start:.20f} seconds") | |
# This is the non-memoized run | |
start = perf_counter() | |
print(f"Result, non-memoized:\t\t{non_memoized_fibo(n)}") | |
end = perf_counter() | |
print(f"Duration, non-memoized:\t\t{end - start:.20f} seconds") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment