0% found this document useful (0 votes)
81 views2 pages

LRU Page Replacement Algorithm Code

The document provides Python implementations for two page replacement algorithms: FIFO and LRU. The FIFO algorithm uses a queue to manage pages and count page faults, while the LRU algorithm utilizes an ordered dictionary to maintain the least recently used pages and track faults. Both algorithms demonstrate their functionality with example page sequences and display the current state of memory and total page faults.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
81 views2 pages

LRU Page Replacement Algorithm Code

The document provides Python implementations for two page replacement algorithms: FIFO and LRU. The FIFO algorithm uses a queue to manage pages and count page faults, while the LRU algorithm utilizes an ordered dictionary to maintain the least recently used pages and track faults. Both algorithms demonstrate their functionality with example page sequences and display the current state of memory and total page faults.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

FIFO Page Replacement Algorithm (Python Code)

Python Code:

from collections import deque

def fifo_page_replacement(pages, capacity):


page_queue = deque()
page_set = set()
page_faults = 0

for page in pages:


if page not in page_set:
page_faults += 1
if len(page_queue) == capacity:
oldest_page = page_queue.popleft()
page_set.remove(oldest_page)
page_queue.append(page)
page_set.add(page)
print(f"Page: {page}, Memory: {list(page_queue)}")

print(f"\nTotal Page Faults: {page_faults}")

pages = [1, 3, 0, 3, 5, 6, 3]
capacity = 3
fifo_page_replacement(pages, capacity)
FIFO Page Replacement Algorithm (Python Code)

LRU Page Replacement Algorithm (Python Code):

from collections import OrderedDict

class LRUCache:
def __init__(self, capacity: int):
self.cache = OrderedDict()
self.capacity = capacity
self.total_page_faults = 0

def get(self, page: int) -> int:


if page not in self.cache:
return -1
self.cache.move_to_end(page)
return self.cache[page]

def put(self, page: int, value: int = None):


if page in self.cache:
self.cache.move_to_end(page)
else:
if len(self.cache) >= self.capacity:
self.cache.popitem(last=False)
self.cache[page] = value
self.total_page_faults += 1

def display(self):
print("Current Cache State:", list(self.cache.keys()))
print("Total Page Faults:", self.total_page_faults)

lru = LRUCache(3)
pages = [1, 2, 3, 1, 4, 5]

for page in pages:


lru.put(page)
lru.display()

You might also like