Created
March 25, 2021 15:53
-
-
Save MMohan1/c1bb819fd67bbf698e1f4dd9778684fa to your computer and use it in GitHub Desktop.
LRU caching using python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Caching: | |
def __init__(self, size=5): | |
self.store = {} | |
self.size = 5 | |
def update_recently_used(self, key): | |
value = self.store.pop(key) | |
self.store[key] = value | |
def get(self, key): | |
value = self.store.get(key, 'Not Found') | |
if value != 'Not Found': | |
self.update_recently_used(key) | |
return value | |
def insert(self, key, value): | |
exists = self.get(key) | |
self.store[key] = value | |
if exists == 'Not Found': | |
self.delete_least_used() | |
def delete_least_used(self): | |
all_keys = list(self.store.keys()) | |
if len(all_keys) > self.size: | |
self.store.pop(all_keys[0]) | |
def delete(self, key): | |
self.store.pop(key, None) | |
def update(self, key, value): | |
exists = self.get(key) | |
if exists == 'Not Found': | |
return 'NF' | |
self.store[key] = value | |
def get_all_values(self): | |
return self.store | |
cach = Caching() | |
print(cach.insert(1, 'a')) | |
print(cach.store) | |
print(cach.insert(2, 'b')) | |
print(cach.store) | |
print(cach.insert(3, 'c')) | |
print(cach.store) | |
print(cach.insert(4, 'd')) | |
print(cach.store) | |
print(cach.insert(5, 'e')) | |
print(cach.store) | |
cach.insert(6, 'f') | |
print(cach.store) | |
print(cach.get(2)) | |
print(cach.store) | |
print(cach.insert(6, 'f')) | |
print(cach.store) | |
print(cach.update(5, 'ee')) | |
print(cach.store) | |
print(cach.delete(3)) | |
print(cach.store) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment