Python LRU Cache Implementation
12. Caching System with LRU Eviction
Write a Python program to create a caching system with support for LRU eviction policy.
The problem entails designing and implementing a caching system that incorporates support for the Least Recently Used (LRU) eviction policy. This entails storing recently accessed items in the cache and evicting the least recently used items when the cache reaches its maximum capacity. The solution should include data structures and algorithms to efficiently manage the cache, track access frequencies, and evict items based on the LRU policy. This caching system can enhance performance by storing frequently accessed data in memory, reducing the need to fetch it from slower storage mediums.
Sample Solution:
Python Code :
Output:
1 -1 3
Explanation:
- Importing libraries:
from collections import OrderedDict: Used to create an ordered dictionary for the cache, maintaining the insertion order of items. - LRUCache Class Definition:
Initialization (__init__): Initializes the cache with a specified capacity and an empty ordered dictionary. - Getting Items (get): Retrieves the value associated with a key from the cache. If the key exists, it moves it to the end of the cache to indicate recent use.
- Putting Items (put): Adds a new key-value pair to the cache. If the cache is at capacity, it evicts the least recently used item before adding the new item.
- Example usage:
Creates an instance of 'LRUCache' with a capacity of 2 and performs various operations (putting and getting items) to demonstrate the LRU eviction policy.
For more Practice: Solve these Related Problems:
- Write a Python program to implement an LRU cache decorator using OrderedDict to cache function outputs.
- Write a Python program to build a custom caching system with an LRU eviction policy using a doubly-linked list and hash map.
- Write a Python program to create a thread-safe LRU cache class that stores computed results and evicts the least recently used items.
- Write a Python program to implement an LRU cache that automatically removes the least accessed items when the cache exceeds its capacity.
Go to:
Previous: Asyncio Concurrent Task Scheduler Implementation in Python.
Next: Asyncio Concurrent Task Scheduler Implementation in Python
Python Code Editor :
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.