diff --git a/src/dsa/caching_memoization.py b/src/dsa/caching_memoization.py index 20390ec..17a31d0 100644 --- a/src/dsa/caching_memoization.py +++ b/src/dsa/caching_memoization.py @@ -6,24 +6,25 @@ def time_based_cache(expiry_seconds: int) -> Callable: """Manual implementation of a time-based cache decorator.""" def decorator(func: Callable) -> Callable: - cache: dict[str, tuple[Any, float]] = {} + cache: dict[tuple, tuple[Any, float]] = {} def wrapper(*args, **kwargs) -> Any: - key_parts = [repr(arg) for arg in args] - key_parts.extend(f"{k}:{repr(v)}" for k, v in sorted(kwargs.items())) - key = ":".join(key_parts) + # Use hashable tuples for the cache key for speed + if kwargs: + key = (args, frozenset(kwargs.items())) + else: + key = (args, None) current_time = time.time() - if key in cache: - result, timestamp = cache[key] + cached = cache.get(key) + if cached is not None: + result, timestamp = cached if current_time - timestamp < expiry_seconds: return result result = func(*args, **kwargs) - cache[key] = (result, current_time) - return result return wrapper @@ -89,4 +90,4 @@ def knapsack(weights: list[int], values: list[int], capacity: int, n: int) -> in return max( values[n - 1] + knapsack(weights, values, capacity - weights[n - 1], n - 1), knapsack(weights, values, capacity, n - 1), - ) \ No newline at end of file + )