Skip to content

Page replacement algorithm, LRU #871

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Oct 28, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions other/least_recently_used.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
from abc import abstractmethod
import sys
from collections import deque

class LRUCache:
""" Page Replacement Algorithm, Least Recently Used (LRU) Caching."""

dq_store = object() # Cache store of keys
key_reference_map = object() # References of the keys in cache
_MAX_CAPACITY: int = 10 # Maximum capacity of cache

@abstractmethod
def __init__(self, n: int):
""" Creates an empty store and map for the keys.
The LRUCache is set the size n.
"""
self.dq_store = deque()
self.key_reference_map = set()
if not n:
LRUCache._MAX_CAPACITY = sys.maxsize
elif n < 0:
raise ValueError('n should be an integer greater than 0.')
else:
LRUCache._MAX_CAPACITY = n

def refer(self, x):
"""
Looks for a page in the cache store and adds reference to the set.
Remove the least recently used key if the store is full.
Update store to reflect recent access.
"""
if x not in self.key_reference_map:
if len(self.dq_store) == LRUCache._MAX_CAPACITY:
last_element = self.dq_store.pop()
self.key_reference_map.remove(last_element)
else:
index_remove = 0
for idx, key in enumerate(self.dq_store):
if key == x:
index_remove = idx
break
self.dq_store.remove(index_remove)

self.dq_store.appendleft(x)
self.key_reference_map.add(x)

def display(self):
"""
Prints all the elements in the store.
"""
for k in self.dq_store:
print(k)

if __name__ == "__main__":
lru_cache = LRUCache(4)
lru_cache.refer(1)
lru_cache.refer(2)
lru_cache.refer(3)
lru_cache.refer(1)
lru_cache.refer(4)
lru_cache.refer(5)
lru_cache.display()