Last active
January 25, 2019 15:37
-
-
Save deque-blog/e602626fd03d528ba5765bfc466e1edb to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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