Skip to content

Instantly share code, notes, and snippets.

@jlsajfj
Last active March 28, 2021 21:22
Show Gist options
  • Save jlsajfj/c6a307bebd02b0d92076e8eb9f3f869c to your computer and use it in GitHub Desktop.
Save jlsajfj/c6a307bebd02b0d92076e8eb9f3f869c to your computer and use it in GitHub Desktop.
Caching functions
#!/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()
@jlsajfj
Copy link
Author

jlsajfj commented Mar 28, 2021

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment