Created
January 25, 2017 20:02
-
-
Save kzahel/84bf5122550c7efa8aaaad4bcf8dcba7 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
import collections | |
class LRUCache: | |
def __init__(self, capacity): | |
self.capacity = capacity | |
self.cache = collections.OrderedDict() | |
def get(self, key): | |
try: | |
value = self.cache.pop(key) | |
self.cache[key] = value | |
return value | |
except KeyError: | |
return -1 | |
def set(self, key, value): | |
try: | |
self.cache.pop(key) | |
except KeyError: | |
if len(self.cache) >= self.capacity: | |
self.cache.popitem(last=False) | |
self.cache[key] = value |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment