Skip to content

Instantly share code, notes, and snippets.

@kzahel
Created January 25, 2017 20:02
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 kzahel/84bf5122550c7efa8aaaad4bcf8dcba7 to your computer and use it in GitHub Desktop.
Save kzahel/84bf5122550c7efa8aaaad4bcf8dcba7 to your computer and use it in GitHub Desktop.
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