Created
August 26, 2021 03:35
-
-
Save ssshukla26/6145717b638d8d286a3a135539617d2f to your computer and use it in GitHub Desktop.
LRU Cache using OrderedDict
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
from collections import OrderedDict | |
class LRUCache: | |
def __init__(self, capacity: int): | |
self.__capacity = capacity | |
self.__cache = OrderedDict() | |
return | |
def get(self, key: int) -> int: | |
# If key already present | |
if key in self.__cache: | |
# Make the key recently used | |
self.__cache.move_to_end(key) | |
return self.__cache[key] | |
return -1 | |
def put(self, key: int, value: int) -> None: | |
# If key already present | |
if key in self.__cache: | |
# Make the key recently used | |
self.__cache.move_to_end(key) | |
else: # If key not present | |
# Remove the least used key, if queue is full | |
if len(self.__cache) == self.__capacity: | |
self.__cache.popitem(False) | |
# Add key value pair to queue | |
self.__cache[key] = value | |
return | |
# Your LRUCache object will be instantiated and called as such: | |
# obj = LRUCache(capacity) | |
# param_1 = obj.get(key) | |
# obj.put(key,value) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment