Skip to content

Commit 42304dc

Browse files
committed
Implement LRU Cache: O(1) operations using OrderedDict
1 parent 134e683 commit 42304dc

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
from collections import OrderedDict
2+
3+
class LruCache:
4+
# It keeps the most recently used items.
5+
# If it gets full, it throws away the item we haven't used for the longest time.
6+
def __init__(self, limit):
7+
if limit <= 0:
8+
raise ValueError("Limit must be positive")
9+
10+
self.limit = limit
11+
# OrderedDict is like a dictionary. It remembers the order of items.
12+
# It handles the O(1) logic for us automatically.
13+
self.cache = OrderedDict()
14+
15+
def get(self, key):
16+
# Trying to find an item
17+
if key not in self.cache:
18+
return None
19+
20+
# If I found it, it means I just "USED" it.
21+
# So I move it to the end (Newest position).
22+
self.cache.move_to_end(key)
23+
return self.cache[key]
24+
25+
def set(self, key, value):
26+
# We are adding or updating an item.
27+
28+
if key in self.cache:
29+
# If it exists, update it and move to the end (Newest).
30+
self.cache.move_to_end(key)
31+
32+
self.cache[key] = value
33+
34+
if len(self.cache) > self.limit:
35+
# Remove the oldest item.
36+
# last=False means "Remove from the beginning (Oldest)".
37+
self.cache.popitem(last=False)

0 commit comments

Comments
 (0)