You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

lru_cache.py 675B

12345678910111213141516171819202122
  1. from collections import OrderedDict
  2. from typing import Any
  3. class LRUCache:
  4. def __init__(self, capacity: int):
  5. self.cache = OrderedDict()
  6. self.capacity = capacity
  7. def get(self, key: Any) -> Any:
  8. if key not in self.cache:
  9. return None
  10. else:
  11. self.cache.move_to_end(key) # move the key to the end of the OrderedDict
  12. return self.cache[key]
  13. def put(self, key: Any, value: Any) -> None:
  14. if key in self.cache:
  15. self.cache.move_to_end(key)
  16. self.cache[key] = value
  17. if len(self.cache) > self.capacity:
  18. self.cache.popitem(last=False) # pop the first item