Added LRU and optimal code (a7).
This commit is contained in:
parent
71d10df55e
commit
4966a50eee
31
Codes/Python version/Assignment-A7 (Page replacement)/LRU.py
Normal file
31
Codes/Python version/Assignment-A7 (Page replacement)/LRU.py
Normal file
@ -0,0 +1,31 @@
|
|||||||
|
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)
|
@ -0,0 +1,44 @@
|
|||||||
|
class Optimal:
|
||||||
|
def __init__(self, capacity):
|
||||||
|
self.capacity = capacity
|
||||||
|
self.cache = []
|
||||||
|
|
||||||
|
def refer(self, page, future):
|
||||||
|
if page not in self.cache:
|
||||||
|
if len(self.cache) < self.capacity:
|
||||||
|
self.cache.append(page)
|
||||||
|
else:
|
||||||
|
farthest_page = self.find_farthest_page(future)
|
||||||
|
index = self.cache.index(farthest_page)
|
||||||
|
self.cache[index] = page
|
||||||
|
|
||||||
|
def find_farthest_page(self, future):
|
||||||
|
farthest = -1
|
||||||
|
farthest_page = None
|
||||||
|
for page in self.cache:
|
||||||
|
if page not in future:
|
||||||
|
return page
|
||||||
|
try:
|
||||||
|
index = future.index(page)
|
||||||
|
if index > farthest:
|
||||||
|
farthest = index
|
||||||
|
farthest_page = page
|
||||||
|
except ValueError:
|
||||||
|
continue
|
||||||
|
return farthest_page
|
||||||
|
|
||||||
|
def display(self):
|
||||||
|
print("Current Pages in Memory (Optimal):", self.cache)
|
||||||
|
|
||||||
|
# Simulate Optimal Page Replacement
|
||||||
|
def optimal_simulation(pages, capacity):
|
||||||
|
optimal = Optimal(capacity)
|
||||||
|
for i in range(len(pages)):
|
||||||
|
optimal.refer(pages[i], pages[i + 1:])
|
||||||
|
optimal.display()
|
||||||
|
|
||||||
|
# Example Pages and Capacity
|
||||||
|
pages = [7, 0, 1, 2, 0, 3, 0, 4]
|
||||||
|
capacity = 3
|
||||||
|
print("\nOptimal Page Replacement Simulation:")
|
||||||
|
optimal_simulation(pages, capacity)
|
Loading…
Reference in New Issue
Block a user