From 4f499604bdc8d0604e6496816e9e21b011627535 Mon Sep 17 00:00:00 2001 From: Samyak Kala <48255425+Sk70249@users.noreply.github.com> Date: Sun, 2 Oct 2022 14:13:22 +0530 Subject: [PATCH] Initial Commit #hacktoberfest #hacktoberfest-accepted #contribute #open-source #hacktoberfest2022 --- Python/Memoization.py | 56 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 Python/Memoization.py diff --git a/Python/Memoization.py b/Python/Memoization.py new file mode 100644 index 00000000..639f8e04 --- /dev/null +++ b/Python/Memoization.py @@ -0,0 +1,56 @@ +def add80(n): + print('Long time') + return n+80 + +print(add80(5)) +print(add80(5)) + +#Memoization 1 + +cache = {} + +def memoizedadd80(n): + if n in cache: + return n + 80 + else: + print('Long time') + cache[n] = n+80 + return cache[n] + +print(memoizedadd80(6)) +print(memoizedadd80(6)) + +#Memoization 2 +def memoizedadd80(): + cache = {} + + def memoized(n): + if n in cache: + return n + 80 + else: + print('Long time') + cache[n] = n+80 + return cache[n] + return memoized + +memo = memoizedadd80() +print(memo(7)) +print(memo(7)) + + + +# https://docs.python.org/3.3/library/functools.html --> Doc for lru_cache + +from functools import lru_cache + +@lru_cache(maxsize = 1000) +def memoized2add80(n): + return n + 80 + + +print(memoized2add80(8)) +print(memoized2add80(8)) +print(memoized2add80.cache_info()) + + +