From 4966a50eee23177a7f7fd5577a3fd5f29f7dd96f Mon Sep 17 00:00:00 2001 From: Kshitij Date: Wed, 6 Nov 2024 15:25:13 +0530 Subject: [PATCH] Added LRU and optimal code (a7). --- .../Assignment-A7 (Page replacement)/LRU.py | 31 +++++++++++++ .../Optimal.py | 44 +++++++++++++++++++ 2 files changed, 75 insertions(+) create mode 100644 Codes/Python version/Assignment-A7 (Page replacement)/LRU.py create mode 100644 Codes/Python version/Assignment-A7 (Page replacement)/Optimal.py diff --git a/Codes/Python version/Assignment-A7 (Page replacement)/LRU.py b/Codes/Python version/Assignment-A7 (Page replacement)/LRU.py new file mode 100644 index 0000000..5be164e --- /dev/null +++ b/Codes/Python version/Assignment-A7 (Page replacement)/LRU.py @@ -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) diff --git a/Codes/Python version/Assignment-A7 (Page replacement)/Optimal.py b/Codes/Python version/Assignment-A7 (Page replacement)/Optimal.py new file mode 100644 index 0000000..67c898d --- /dev/null +++ b/Codes/Python version/Assignment-A7 (Page replacement)/Optimal.py @@ -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)