帮我写一个python版的LRU算法
时间: 2023-03-07 08:20:23 浏览: 164
我可以为你提供一个python版的LRU算法的示例代码:class LRUCache:
def __init__(self, capacity):
self.capacity = capacity
self.cache = {}
self.used = [] def get(self, key):
if key in self.cache:
self.used.remove(key)
self.used.append(key)
return self.cache[key]
else:
return -1 def set(self, key, value):
if key in self.cache:
self.cache[key] = value
self.used.remove(key)
self.used.append(key)
else:
if len(self.used) >= self.capacity:
oldest = self.used[0]
self.cache.pop(oldest)
self.used.remove(oldest)
self.cache[key] = value
self.used.append(key)
阅读全文