Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

How to build a Least Recently Used (LRU) cache, in Python?

"""
The below code provides an implementation
for a Least Recently Used (LRU) cache.

An LRU cache:
1. discards the least recently used item if cache is full
2. places a new item at the front of the cache
3. returns a requested item and then places it at front of cache. 

Time complexity: O(1) for put and get methods
Space complexity: O(capacity of LRU cache) 
"""
from collections import OrderedDict

class LRUCache(OrderedDict):
    # Initialize capacity of cache
    def __init__(self, capacity):
        self.capacity = capacity

    # Get the item associated with key
    def get(self, key):
        if key not in self:
            return - 1
        # Move requested item to front of cache
        self.move_to_end(key, last=False)
        return self[key]

    def put(self, key, value):
        # Insert/Update item
        self[key] = value
        # Move new item to front of cache
        self.move_to_end(key, last=False)
        # Apply cache eviction policy
        # Removing the item at end of cache
        # i.e., the least recently used item
        if len(self) > self.capacity:
            self.popitem()

cache = LRUCache(2)
cache.put("First item", 1)
cache.put("Second item", 2)
# Cache content: "Second item": 2, "First item": 1
print(cache.get("First item"))  # 1
# Cache content: "First item": 1, "Second item": 2
cache.put("Third item", 3)
# Cache content: "Third item": 3, "First item": 1
print(cache.get("Second item"))  # -1
Comment

PREVIOUS NEXT
Code Example
Python :: Object of type datetime is not JSON serializable 
Python :: programmer tool 
Python :: how to allow a range of numbers for example 1 to 14 on regular expression python 
Python :: change group box border color pyqt5 
Python :: numpy sum 
Python :: selenium session id python 
Python :: how to get left click input in pygame 
Python :: pascal triangle 
Python :: python integers 
Python :: python db access though ssh user 
Python :: install requests-html with conda 
Python :: get script text selenium python 
Python :: 0x80370102 kali linux 
Python :: pdfs in django 
Python :: Python use number twice without assignment 
Python :: wordcount pyspark 
Python :: python get function docstring 
Python :: all python statements 
Python :: midpoint circle drawing algorithm 
Python :: shared SHMEM python 
Python :: django delete table data 
Python :: boto3 upload dataframe directly to s3 
Python :: repeat a condition n times one by one python 
Python :: convert numpy array to HSV cv 
Python :: python tkinter cheat sheet 
Python :: how to iterate a list in reverse order in python with index 
Python :: pyplot x vs y 
Python :: puthon for loop 
Python :: is plaindrome python 
Python :: music distorted on discord 
ADD CONTENT
Topic
Content
Source link
Name
5+9 =