Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

Least recently used cache

"""
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 :: how to check if a key is present in python dictionary 
Python :: wails install 
Python :: horizontal line to the y axis in matplotlib 
Python :: pytest snapshot update 
Python :: numpy percentile 
Python :: how to input sentence in python 
Python :: python derivative of mean squared error 
Python :: reverse string in python without using function 
Python :: get diagonals of 2d array 
Python :: Python get the name of the song that is playing 
Python :: convert string ranges list python 
Python :: set lable of field django 
Python :: how draw shell in python 
Python :: get values from list of dictionaries python 
Python :: jupyter dataframe print all 
Python :: python np array get dimantion 
Python :: how to comment python 
Python :: convert plt.show to image to show opencv 
Python :: mid point circle drawing 
Python :: get dummies pandas 
Python :: sklearn tree visualization 
Python :: how to loop function until true python 
Python :: looping over dictionary python 
Python :: tkinter insert value box 
Python :: python sh command 
Python :: how to put my graph in tkinter interface 
Python :: 12 month movinf average in python for dataframe 
Python :: django get all model fields 
Python :: dynamic printing 
Python :: tkinter auto resize height 
ADD CONTENT
Topic
Content
Source link
Name
1+6 =