Advertisement
MathQ_

Untitled

Oct 24th, 2022
916
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.64 KB | None | 0 0
  1. from collections import deque
  2.  
  3.  
  4. def cache(n):
  5.     lru_cache = dict()
  6.     order = deque()
  7.  
  8.     def decorator(function):
  9.         def wrapped(*args, **kwargs):
  10.             nonlocal lru_cache, order
  11.             query = str(args) + str(kwargs)
  12.             if lru_cache.get(query, None) is None:
  13.                 order.append(query)
  14.                 value = function(*args, **kwargs)
  15.                 lru_cache[query] = value
  16.                 if len(order) > n:
  17.                     del lru_cache[order[0]]
  18.                     order.popleft()
  19.             else:
  20.                 return lru_cache[query]
  21.  
  22.         return wrapped
  23.  
  24.     return decorator
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement