Advertisement
Korotkodul

Задача 2. LRU

Oct 24th, 2024 (edited)
43
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.78 KB | None | 0 0
  1. from typing import (
  2.     Callable,
  3.     TypeVar,
  4. )
  5. from functools import wraps
  6.  
  7.  
  8. T = TypeVar("T")
  9.  
  10.  
  11. def lru_cache(capacity: int) -> Callable[[T], T]:
  12.     try:
  13.         capacity = round(capacity)
  14.     except:
  15.         raise TypeError
  16.     if capacity < 1:
  17.         raise ValueError
  18.     res = {}
  19.  
  20.     def take_in_func(func):
  21.         @wraps(func)
  22.         def wrapper(*args, **kwargs):
  23.             arg = args[0]
  24.             if arg not in res:
  25.                 res[arg] = func(*args, **kwargs)
  26.                 if len(res) > capacity:
  27.                     for k in res.keys():
  28.                         res.pop(k)
  29.                         break
  30.             else:
  31.                 res[arg] = res.pop(arg)
  32.             return res[arg]
  33.         return wrapper
  34.     return take_in_func
  35.  
  36.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement