3
1
SystemsProgrammingAndOperat.../Codes/Python version/Assignment-A7 (Page replacement)/LRU.py

32 lines
901 B
Python

class LRU:
def __init__(self, capacity):
self.capacity = capacity
self.cache = {}
self.order = []
def refer(self, page):
if page not in self.cache:
if len(self.cache) >= self.capacity:
lru_page = self.order.pop(0) # Remove least recently used page
del self.cache[lru_page]
else:
self.order.remove(page) # Remove page to update its order
self.cache[page] = True
self.order.append(page)
def display(self):
print("Current Pages in Memory (LRU):", list(self.cache.keys()))
# Simulate LRU
def lru_simulation(pages, capacity):
lru = LRU(capacity)
for page in pages:
lru.refer(page)
lru.display()
# Example Pages and Capacity
pages = [7, 0, 1, 2, 0, 3, 0, 4]
capacity = 3
print("LRU Page Replacement Simulation:")
lru_simulation(pages, capacity)