Here is my simple code for LRU cache in Python 2.7. Appreciate if anyone could review for logic correctness and also potential performance improvements.
A confusion want to ask for advice is, I am using a list
to track access time, the first element of the list the is least time accessed, and the last element is the most recent accessed element. And I am using remove
method of list
, for example, statement accessQueue.remove(key)
, wondering what is the time complexity of list.remove
, is it linear or log(N)?
from collections import defaultdict kvStore = defaultdict(str) accessQueue = [] maxSize = 10 def cacheSet(key, value): kvStore[key] = value if key in accessQueue: accessQueue.remove(key) accessQueue.append(key) else: accessQueue.append(key) if len(accessQueue) > maxSize: accessQueue.pop(0) def cacheGet(key): if key in kvStore: accessQueue.remove(key) accessQueue.append(key) return kvStore[key] else: return None def cachePrint(): for k,v in kvStore.items(): print k,v if __name__ == "__main__": for i in range(10): cacheSet(i, "value " + str(i)) for i in range(10): print cacheGet(i) cacheSet(11, "value " + str(11)) cachePrint()