CodeUsed:-
#LRU cache using Ordered Dict
from collections import OrderedDict
class LRUCache:
def __init__(self, capacity: int):
self.cache = OrderedDict()
self.capacity = capacity
def get(self, key: int) ➡️ int:
if key not in self.cache:
return -1
# Move accessed key to the end (most recently used)
self.cache.move_to_end(key)
return self.cache[key]
def put(self, key: int, value: int) ➡️ None:
if key in self.cache:
# Update existing key and move to end
self.cache.move_to_end(key)
self.cache[key] = value
if len(self.cache)▶️ self.capacity:
# Pop the least recently used item (first item)
self.cache.popitem(last=False)
# Example Usage
lru = LRUCache(2)
lru.put(1, 1)
lru.put(2, 2)
print(lru.get(1)) # Output: 1
lru.put(3, 3) # Evicts key 2
print(lru.get(2)) # Output: -1
lru.put(4, 4) # Evicts key 1
print(lru.get(1)) # Output: -1
print(lru.get(3)) # Output: 3
print(lru.get(4)) # Output: 4
#coding #python #programming #shorts
Did you miss our previous article...
https://learningvideos.club/computer-technology/ep-1-introduction-to-python-python-tutorial-for-beginners-2025