Least Recently Used Page Replacement Algorithm Python ProgramPage replacement algorithms are required in OS to employ paging techniques to manage memory to determine which page has to be removed when a new page is added. Every time a new page is referenced but not already in memory, a page fault happens, and the OS replaces the referenced page with the latest referenced page. Various page replacement algorithms offer various recommendations for selecting the appropriate replacement page. Every algorithm strives to decrease the number of page faults. The Least Recently Used (LRU) algorithm is a Greedy algorithm. In this algorithm, the page to be replaced is least recently used. The idea is based on the locality of reference. The least recently used page is considered to be of less importance. Let us take an example. We have a string determining the sequence of page reference 3 0 1 2 1 3 5 1 2 5 0 1 2. We have the capacity of page slots equal to 3.
Approach-1Let C be the capacity of the total number of pages the memory can hold. Let S be the set containing the pages currently present in the memory.
Code Output: s = {3} s = {0, 3} s = {0, 1, 3} s = {0, 1, 2} s = {0, 1, 2} s = {3, 1, 2} s = {1, 3, 5} s = {1, 3, 5} s = {1, 2, 5} s = {1, 2, 5} s = {0, 2, 5} s = {0, 1, 5} s = {0, 2, 1} The total number of page faults is: 10 Time Complexity: The average time complexity of the set and the map operations is O(1). In the worst-case scenario, the complexity will go to O(n). But, since O(n) is the dominant term, this program's time complexity is O(n). Space Complexity: The space complexity will equal the given capacity of holding pages. Approach-2: (Without using HashMap)We will not use a set in this approach. Below is the algorithmic approach:
Below is the code to implement this algorithm in Python: Code Output: s = [3] s = [3, 0] s = [3, 0, 1] s = [0, 1, 2] s = [0, 2, 1] s = [2, 1, 3] s = [1, 3, 5] s = [3, 5, 1] s = [5, 1, 2] s = [1, 2, 5] s = [2, 5, 0] s = [5, 0, 1] s = [0, 1, 2] The total number of page faults is: 10 Time Complexity: The time complexity of this LRU algorithm is O(n). The reason behind this time complexity is that we have used a linear for loop to traverse the given sequence of page referencing. The page faults are executed in constant time. Space Complexity: The space complexity of this LRU algorithm is O(n). Here n is the length of the given sequence of page referencing. In this program, we can also determine the total number of page hits that have taken place throughout the simulation. We need to create another variable that stores the count for the page hits. The number of times the current page was already in the memory is called page hits. Next TopicNumber patterns in Python |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India