From 6a9d3d181d815e265e26f210caa89f6c288f79c3 Mon Sep 17 00:00:00 2001 From: Dmytro Minyaylo Date: Wed, 22 Jan 2025 18:42:08 +0200 Subject: [PATCH 1/2] solution py-cache-decorator --- app/main.py | 39 ++++++++++++++++++++++++++++++++++++--- 1 file changed, 36 insertions(+), 3 deletions(-) diff --git a/app/main.py b/app/main.py index 68287892..156bb211 100644 --- a/app/main.py +++ b/app/main.py @@ -1,6 +1,39 @@ -from typing import Callable +from typing import Callable, Any +from functools import wraps def cache(func: Callable) -> Callable: - # Write your code here - pass + cache_storage = {} + + @wraps(func) + def wrapper(*args) -> Callable: + if not all(isinstance(arg, (int, float, str, tuple, bool)) + for arg in args): + raise TypeError("Only immutable argument types") + key = (func.__name__, args) + if key in cache_storage: + print("Getting from cache") + return cache_storage[key] + print("Calculating new result") + cache_storage[key] = func(*args) + return cache_storage[key] + return wrapper + + +@cache +def long_time_func(base: int, exponent: int, multiplier: int) -> int: + return (base ** exponent ** multiplier) % (base * multiplier) + + +@cache +def long_time_func_2(n_tuple: tuple, power: int) -> Any: + return [number ** power for number in n_tuple] + + +if __name__ == "__main__": + print(long_time_func(1, 2, 3)) + print(long_time_func(2, 2, 3)) + print(long_time_func_2((5, 6, 7), 5)) + print(long_time_func(1, 2, 3)) + print(long_time_func_2((5, 6, 7), 10)) + print(long_time_func_2((5, 6, 7), 10)) From 0b6fab60ec8259c4a240d30ff6f5180da8713d99 Mon Sep 17 00:00:00 2001 From: Dmytro Minyaylo Date: Wed, 22 Jan 2025 19:01:34 +0200 Subject: [PATCH 2/2] updated py-cache-decorator --- app/main.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/app/main.py b/app/main.py index 156bb211..47491ebb 100644 --- a/app/main.py +++ b/app/main.py @@ -6,7 +6,7 @@ def cache(func: Callable) -> Callable: cache_storage = {} @wraps(func) - def wrapper(*args) -> Callable: + def wrapper(*args) -> Any: if not all(isinstance(arg, (int, float, str, tuple, bool)) for arg in args): raise TypeError("Only immutable argument types") @@ -26,8 +26,8 @@ def long_time_func(base: int, exponent: int, multiplier: int) -> int: @cache -def long_time_func_2(n_tuple: tuple, power: int) -> Any: - return [number ** power for number in n_tuple] +def long_time_func_2(n_tuple: tuple, power: int) -> tuple: + return tuple(number ** power for number in n_tuple) if __name__ == "__main__":