algorithm-in-python/dataStructure/LRU/lru_orderedDict.py

26 lines
770 B
Python
Raw Normal View History

2019-06-11 16:26:24 +08:00
''' mbinary
#########################################################################
# File : lru_orderedDict.py
# Author: mbinary
# Mail: zhuheqin1@gmail.com
# Blog: https://mbinary.xyz
# Github: https://github.com/mbinary
# Created Time: 2019-05-23 20:13
# Description:
#########################################################################
'''
2019-05-23 23:51:44 +08:00
class LRUCache(object):
def __init__(self, capacity):
self.od, self.cap = collections.OrderedDict(), capacity
def get(self, key):
if key not in self.od: return -1
self.od.move_to_end(key)
return self.od[key]
def put(self, key, value):
if key in self.od: del self.od[key]
elif len(self.od) == self.cap: self.od.popitem(False)
self.od[key] = value