Skip to content

Instantly share code, notes, and snippets.

@wilfreddesert
Created February 11, 2021 16:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wilfreddesert/553b27c1d4376871d04a0eb883a686a0 to your computer and use it in GitHub Desktop.
Save wilfreddesert/553b27c1d4376871d04a0eb883a686a0 to your computer and use it in GitHub Desktop.
class LRUCache:
"""
https://en.wikipedia.org/wiki/Cache_replacement_policies#Least_recently_used_(LRU)
"""
def __init__(self, maxsize: int = 16) -> None:
self.cache = {}
self.maxsize = maxsize
def put(self, key: Hashable, value: Any) -> None:
"""Time Complexity: O(1)"""
if key in self.cache:
self.cache.pop(key)
self.cache[key] = value
if len(self.cache) > self.maxsize:
first_key = next(iter(self.cache))
self.cache.pop(first_key)
def get(self, key: Hashable) -> Any:
"""Time Complexity: O(1)"""
current_element = self.cache.get(key)
if current_element is not None:
self.cache.pop(key)
self.cache[key] = current_element
return current_element
raise KeyError("No such key in this cache")
def exists(self, key: Hashable) -> bool:
"""Time Complexity: O(1)"""
return key in self.cache
def size(self) -> int:
"""Time Complexity: O(1)"""
return len(self.cache)
def __repr__(self):
return f"LRUCache({self.cache})"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment