Last active
June 6, 2022 08:22
-
-
Save raymondng76/074ac906fd1be07b4152db4e4d3a91da to your computer and use it in GitHub Desktop.
Memoize Example #python #memoize
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
# Memoize example which stores results for fast look ups | |
import time | |
def memoize(func): | |
cache = {} | |
def wrapper(*args, **kwargs): | |
if (args, kwargs) not in cache: | |
cache[(args, kwargs)] = func(*args, **kwargs) | |
return cache[(args, kwargs)] | |
return wrapper | |
@memoize | |
def sleep_add_func(a, b): | |
print(f'sleeping...') | |
time.sleep(5) | |
return a + b | |
if __name__ == '__main__': | |
print(sleep_add_func(1, 5)) # output shows that the lines within sleep_add_func is called | |
########## | |
# sleeping... | |
# 6 | |
########## | |
print(sleep_add_func(1, 5)) # output shows the results are immediately returned without executing the lines | |
########## | |
# 6 | |
########## |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment