Skip to content

Commit eb34b84

Browse files
committed
implement LRU cache using OrderedDict
Was going to use my own linked list, this was easier.
1 parent f13588d commit eb34b84

1 file changed

Lines changed: 26 additions & 0 deletions

File tree

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
from collections import OrderedDict
2+
"""
3+
Was gonna implement my own using a dict to to store keys and
4+
my own doubly linked list to do the ordering. I'm not 100% sure about the complexity
5+
of the OrderedDict, but it should be O(1) for get and set.
6+
"""
7+
8+
class LruCache:
9+
def __init__(self, limit):
10+
if limit <= 0:
11+
raise ValueError("Limit must be greater than 0")
12+
self.limit = limit
13+
self.data = OrderedDict()
14+
15+
def get(self, key):
16+
if key not in self.data:
17+
return None
18+
self.data.move_to_end(key) # end is most recent
19+
return self.data[key]
20+
21+
def set(self, key, value):
22+
if key in self.data:
23+
self.data.move_to_end(key)
24+
self.data[key] = value
25+
if len(self.data) > self.limit:
26+
self.data.popitem(last=False)

0 commit comments

Comments
 (0)