-
-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathlru_cache.py
More file actions
30 lines (18 loc) · 632 Bytes
/
lru_cache.py
File metadata and controls
30 lines (18 loc) · 632 Bytes
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
from collections import OrderedDict
class LruCache:
def __init__(self, limit):
if limit <= 0:
raise ValueError("Limit must be positive")
self.limit = limit
self.cache = OrderedDict()
def get(self, key):
if key not in self.cache:
return None
self.cache.move_to_end(key)
return self.cache[key]
def set(self, key, value):
if key in self.cache:
self.cache.move_to_end(key)
self.cache[key] = value
if len(self.cache) > self.limit:
self.cache.popitem(last=False)