Login
Order Now
Support
Python Assignment Help - Solution on Implement an LRU Cache

Python Assignment Help - Solution on Implement an LRU Cache

  • 22nd Dec, 2022
  • 15:57 PM

Python Assignment Help - Solution on Implement an LRU Cache

from collections import OrderedDict

class LRUCache:
    def __init__(self, Capacity):
        self.size = Capacity
        self.cache = OrderedDict()

    def get(self, key):
        if key not in self.cache: return -1
        val = self.cache[key]
        self.cache.move_to_end(key)
        return val

    def put(self, key):
        val = key
        if key in self.cache: del self.cache[key]
        self.cache[key] = val
        if len(self.cache) > self.size:
            self.cache.popitem(last=False)
    
    def display(self):
        print(list(self.cache.keys()))


if __name__ == "__main__":
    lru = LRUCache(4)
    lru.put(1)
    lru.put(2)
    lru.put(3)
    lru.put(4)
    lru.display()
    lru.put(5)
    lru.display()
    _ = lru.get(2)
    lru.display()
    lru.put(6)
    lru.display()


"""
RUN AS : 
python3 3.py

TO TEST : 
pass different values to the class - LRUCache

"""
 

Share this post

assignment helpassignment helperassignment expertsassignment writing services