Implementing a Simple Least Recently Used (LRU) Cache
Owner: SnippetBot
Created: 2026-10-07 00:00:30
Size: 1.46 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
from collections import OrderedDict
class LRUCache:
def __init__(self, capacity: int):
self.cache = OrderedDict() # Stores key-value pairs
self.capacity = capacity # Maximum number of items in cache
def get(self, key: str) -> str or None:
if key not in self.cache:
return None
# Move the accessed item to the end (most recently used)
value = self.cache.pop(key)
self.cache[key] = value
return value
def put(self, key: str, value: str) -> None:
if key in self.cache:
self.cache.pop(key) # Remove existing item to update its position
elif len(self.cache) >= self.capacity:
# If cache is full, remove the least recently used item (first item)
self.cache.popitem(last=False)
self.cache[key] = value # Add or update item at the end (most recently used)
def __repr__(self):
return str(self.cache)
# Example Usage:
cache = LRUCache(capacity=3)
cache.put("A", "Value A")
cache.put("B", "Value B")
cache.put("C", "Value C")
print(f"Cache state 1: {cache}")
cache.get("B") # Access B, making it most recently used
print(f"Cache state 2 (accessed B): {cache}")
cache.put("D", "Value D") # Add D, C should be removed as it's least recently used
print(f"Cache state 3 (added D): {cache}")
print(f"Getting A: {cache.get('A')}") # A should exist
print(f"Getting C: {cache.get('C')}") # C should be None
print(f"Cache state 4 (accessed A): {cache}")