Skip to content

Commit dd86daa

Browse files
authored
Create LRU Cache 1
1 parent 0d91e90 commit dd86daa

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

interview_query/LRU Cache 1

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
Create a class named LRUCache that implements the behavior expected of a Least Recently Used (LRU) Cache.
2+
3+
The LRUCache class implements the following methods:
4+
5+
__init__(self, capacity) - initializes the object and takes in a capacity parameter specifying the maximum capacity of the cache.
6+
get_if_exists(self, key) -> Any|None - gets a value based on a key. If the key exists, returns the associated value. If the key has expired or did not exist in the first place, returns None.
7+
put(self, key, value) - places a value inside the cache. In the case wherein the cache is full, invalidates the least recently used element. When two keys collide, the older value should be invalidated in place of the new one.
8+
---------------------------------------------------------------------------------------------------------------------
9+
10+
from typing import Any
11+
import collections
12+
class LRUCache:
13+
14+
def __init__(self, capacity):
15+
self.capacity = capacity
16+
self.d = collections.OrderedDict()
17+
18+
19+
def get_if_exists(self, key) -> Any | None:
20+
if key not in self.d:
21+
return None
22+
self.d.move_to_end(key)
23+
return self.d[key]
24+
25+
def put(self, key, value):
26+
if key in self.d:
27+
self.d.move_to_end(key)
28+
29+
self.d[key]= value
30+
if len(self.d) > self.capacity:
31+
self.d.popitem(False)
32+

0 commit comments

Comments
 (0)