Skip to content

Instantly share code, notes, and snippets.

@deque-blog
Last active January 25, 2019 15:37
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 deque-blog/e602626fd03d528ba5765bfc466e1edb to your computer and use it in GitHub Desktop.
Save deque-blog/e602626fd03d528ba5765bfc466e1edb to your computer and use it in GitHub Desktop.
class LRUCache:
def __init__(self, max_size):
self.dict = OrderedDict()
self.max_size = max_size
def __len__(self):
return len(self.dict)
def __contains__(self, key):
if key in self.dict:
self.dict.move_to_end(key, last=False) # Move to beginning
return True
return False
def __setitem__(self, key, value):
self.dict[key] = value
self.dict.move_to_end(key, last=False) # Move to beginning
if len(self) > self.max_size:
self.dict.popitem(last=True) # Pop the last key
def __getitem__(self, key):
val = self.dict.get(key)
if val is not None:
self.dict.move_to_end(key, last=False) # Move to beginning
return val
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment