Skip to content

Instantly share code, notes, and snippets.

@ssshukla26
Created August 26, 2021 03:35
Show Gist options
  • Save ssshukla26/6145717b638d8d286a3a135539617d2f to your computer and use it in GitHub Desktop.
Save ssshukla26/6145717b638d8d286a3a135539617d2f to your computer and use it in GitHub Desktop.
LRU Cache using OrderedDict
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