forked from kumaya/python-programs
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLRUcache.py
More file actions
Latest commit
42 lines (35 loc) · 1.07 KB
/
Copy pathLRUcache.py
File metadata and controls
42 lines (35 loc) · 1.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# test implementation of LRU cache.
fromcollectionsimportOrderedDict
classLRUCache(object):
def__init__(self, capacity):
self.__capacity=capacity
self.__cache=OrderedDict()
defset(self, key, value):
try:
self.__cache.pop(key)
exceptKeyError:
iflen(self.__cache) >=self.__capacity:
self.__cache.popitem(last=False)
self.__cache[key] =value
defget(self, key):
try:
value=self.__cache.pop(key)
self.__cache[key] =value
returnvalue
exceptKeyError:
return-1
defget_cache_details(self):
returnself.__cache
if__name__=="__main__":
cache=LRUCache(2)
cache.set('name', 'john')
cache.set('age', '12')
printcache.get_cache_details()
cache.set('name', 'doey')
printcache.get_cache_details()
printcache.get('age')
printcache.get_cache_details()
cache.set('aaa', 'aaaaa')
printcache.get_cache_details()
printcache.get('age')
printcache.get_cache_details()