medium +30 pts

LRU Memoize

Implement an LRU caching decorator with manual eviction using OrderedDict.

Write a decorator factory `lru_memoize(maxsize)` that returns a decorator. When applied to a function, the decorated function caches results using a least-recently-used (LRU) policy with capacity `maxsize`. Rules: - Build a hashable cache key from both positional and keyword arguments (all arguments are hashable). - On a cache hit, move the entry to most-recently-used position and return the cached result. - On a cache miss, if cache is full, evict the least-recently-used entry before storing the new result. - If `maxsize == 0`, the decorator should not cache; every call invokes the original function. - The decorated function must preserve the original function's `__name__` and `__doc__`. Implement the LRU logic yourself. You may use `collections.OrderedDict` but not `functools.lru_cache` or other caching libraries. Signature: ```python def lru_memoize(maxsize): ... ``` Usage: ```python @lru_memoize(2) def add(a, b): return a + b ``` You must also define decorated functions for testing: - `cached_add = lru_memoize(2)(lambda a, b: a + b)` - `cached_greet = lru_memoize(1)(lambda name, greeting="Hello": f"{greeting}, {name}!")` - `cached_pow = lru_memoize(3)(lambda base, exp: base ** exp)` - `cached_counter = lru_memoize(0)(lambda: ...)` where the underlying function increments a counter and returns the count (to verify no caching). Your submitted solution must define these names exactly.

Constraints

- `maxsize` is an integer >= 0. - All function arguments are hashable. - Number of distinct calls is at most 1000. - Expected O(1) average time per cache operation.

Example

```python
cached_add = lru_memoize(2)(lambda a, b: a + b)
print(cached_add(1, 2))  # 3
print(cached_add(2, 3))  # 5
print(cached_add(1, 2))  # 3 (cached)
print(cached_add(3, 4))  # 7 (evicts (1,2))
print(cached_add(1, 2))  # 3 (recomputed)

cached_greet = lru_memoize(1)(lambda name, greeting="Hello": f"{greeting}, {name}!")
print(cached_greet("Alice"))        # Hello, Alice!
print(cached_greet("Bob", "Hi"))    # Hi, Bob!
print(cached_greet("Alice"))        # Hello, Alice! (recomputed)
```
30 points ~25 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Use an OrderedDict for the cache; `move_to_end` marks recent use.
On cache hit, call `move_to_end` before returning.
On insert when full, `popitem(last=False)` removes oldest.
For maxsize 0, return a wrapper that just calls the function.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.