Last active
March 28, 2021 21:22
-
-
Save jlsajfj/c6a307bebd02b0d92076e8eb9f3f869c to your computer and use it in GitHub Desktop.
Caching functions
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
#!/usr/bin/python3.9 | |
cfd = dict()# cfd for cache_func_dict | |
def cache(func): | |
def wrapper(*args, **kwargs): | |
val = None | |
if func in cfd: | |
inner_dict = cfd[func] | |
if args in inner_dict: | |
val = inner_dict[args] | |
else: | |
val = func(*args, **kwargs) | |
cfd[func][args] = val | |
else: | |
val = func(*args, **kwargs) | |
cfd[func] = dict() | |
cfd[func][args] = val | |
return val | |
return wrapper | |
@cache | |
def fib(a: int) -> int: | |
if a < 2: | |
return a# start with 0 1 | |
return fib(a-1)+fib(a-2) | |
def main(): | |
for _ in range(401): | |
print(f'{_}: {fib(_)}') | |
for _ in range(401): | |
print(f'{_}: {fib(_)}') | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I saw that python's adding a cache decorator, to allow for memoization without much added difficulty. Just saw a video on wrappers and thought I'd give it a shot. Works but I need another case.