Created
June 12, 2015 16:28
-
-
Save damzam/4b0812c997e91f1bed17 to your computer and use it in GitHub Desktop.
Implement a simple LRUCache in Python
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
#!/usr/bin/env python | |
""" | |
Python's OrderedDict is an ideal data structure | |
to create an LRU cache | |
""" | |
from collections import OrderedDict | |
class LRUCache(object): | |
def __init__(self, max_length=100000): | |
self.cache = OrderedDict() | |
self.max_length = max_length | |
def __setitem__(self, key, value): | |
if key in self.cache: | |
self.cache.pop(key) | |
self.cache[key] = value | |
if len(self.cache) > self.max_length: | |
self.cache.popitem(last=False) | |
def __getitem__(self, key): | |
if key in self.cache: | |
value = self.cache.pop(key) | |
self.cache[key] = value | |
return value | |
else: | |
raise KeyError | |
def main(): | |
cache = LRUCache(3) | |
cache[1] = 2 | |
cache[2] = 3 | |
cache[3] = 4 | |
cache[4] = 5 | |
cache[1] = 2 | |
assert cache[1] == 2 | |
try: | |
cache[2] | |
except KeyError: | |
pass | |
else: | |
raise Exception('This should have thrown a KeyError') | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment