Last active
July 22, 2020 09:44
-
-
Save hiepph/777e7036b5e3639257f6000672f854b7 to your computer and use it in GitHub Desktop.
This file contains 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
# ref: https://www.geeksforgeeks.org/lru-cache-in-python-using-ordereddict/ | |
from collections import OrderedDict | |
class LRUCache: | |
def __init__(self, capacity): | |
self.cache = OrderedDict() | |
self.capacity = capacity | |
def get(self, k): | |
if k not in self.cache: | |
return -1 | |
else: | |
self.cache.move_to_end(k) | |
return self.cache[k] | |
def put(self, k, v): | |
self.cache[k] = v | |
self.cache.move_to_end(k) | |
if len(self.cache) > self.capacity: | |
self.cache.popitem(last=False) # pop first item | |
if __name__ == '__main__': | |
cache = LRUCache(2) | |
cache.put(1, 1) | |
print(cache.cache) | |
cache.put(2, 2) | |
print(cache.cache) | |
cache.get(1) | |
print(cache.cache) | |
cache.put(3, 3) | |
print(cache.cache) | |
cache.get(2) | |
print(cache.cache) | |
cache.put(4, 4) | |
print(cache.cache) | |
cache.get(1) | |
print(cache.cache) | |
cache.get(3) | |
print(cache.cache) | |
cache.get(4) | |
print(cache.cache) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment