Fast and succinct LRU cache implementation


  • 0
    P
    import collections
    
    class LRUCache(object):
    
        def __init__(self, capacity):
            self.cache = collections.OrderedDict()
            self.capacity = capacity
    
        def get(self, key):
            try:
                value = self.cache.pop(key)
                self.cache[key] = value
                return value
            except KeyError:
                return -1
    
        def put(self, key, value):
            try:
                self.cache.pop(key)
            except KeyError:
                if len(self.cache) >= self.capacity:
                    self.cache.popitem(last=False)
            self.cache[key] = value
    

    python -m cProfile lru-cache-test.py ordered-lru-cache
    ... ...
    lrucache took 0.122 sec
    149493 function calls (149490 primitive calls) in 0.138 seconds


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.