From 15de46b43a028fc2257335d2bb31f62f0100fba0 Mon Sep 17 00:00:00 2001 From: Severyn Krok Date: Fri, 29 Sep 2023 16:10:12 +0300 Subject: [PATCH 1/3] Implement py-cache-decorator --- app/main.py | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/app/main.py b/app/main.py index 68287892..d30e2ccc 100644 --- a/app/main.py +++ b/app/main.py @@ -2,5 +2,17 @@ def cache(func: Callable) -> Callable: - # Write your code here - pass + cached_arguments = [] + cached_results = [] + + def wrapper(*args, **kwargs) -> int: + if args in cached_arguments or kwargs in cached_arguments: + print("Getting from cache") + return cached_results[cached_arguments.index(args)] + else: + cached_arguments.append(args) + cached_results.append(func(*args, **kwargs)) + print("Calculating new result") + return cached_results[-1] + + return wrapper From ca2ca7f9cd33825607994281a51d463ccf0479a6 Mon Sep 17 00:00:00 2001 From: Severyn Krok Date: Fri, 29 Sep 2023 16:20:48 +0300 Subject: [PATCH 2/3] v_2 --- app/main.py | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/app/main.py b/app/main.py index d30e2ccc..9cbcac53 100644 --- a/app/main.py +++ b/app/main.py @@ -2,17 +2,14 @@ def cache(func: Callable) -> Callable: - cached_arguments = [] - cached_results = [] + cached_results = {} - def wrapper(*args, **kwargs) -> int: - if args in cached_arguments or kwargs in cached_arguments: + def wrapper(*args) -> int: + if args in cached_results: print("Getting from cache") - return cached_results[cached_arguments.index(args)] else: - cached_arguments.append(args) - cached_results.append(func(*args, **kwargs)) + cached_results[args] = func(*args) print("Calculating new result") - return cached_results[-1] + return cached_results[args] return wrapper From 1164a84456b301ca8f05e030e7042e93b59fe142 Mon Sep 17 00:00:00 2001 From: Severyn Krok Date: Fri, 29 Sep 2023 21:00:04 +0300 Subject: [PATCH 3/3] v_2.1 --- app/main.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/app/main.py b/app/main.py index 9cbcac53..a49d4fa8 100644 --- a/app/main.py +++ b/app/main.py @@ -7,9 +7,9 @@ def cache(func: Callable) -> Callable: def wrapper(*args) -> int: if args in cached_results: print("Getting from cache") - else: - cached_results[args] = func(*args) - print("Calculating new result") + return cached_results[args] + cached_results[args] = func(*args) + print("Calculating new result") return cached_results[args] return wrapper