Skip to content

Commit c6d217f

Browse files
Cédrick ChaudCédrick Chaud
Cédrick Chaud
authored and
Cédrick Chaud
committed
adding lru cache optmizer functionality
1 parent 21be7f3 commit c6d217f

File tree

2 files changed

+67
-0
lines changed

2 files changed

+67
-0
lines changed

lru_cache.py

+61
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
class Node:
2+
def __init__(self, key, value):
3+
self.key = key
4+
self.value = value
5+
self.prev = None
6+
self.next = None
7+
8+
class LRUCache(object):
9+
10+
def __init__(self, capacity):
11+
"""
12+
:type capacity: int
13+
"""
14+
self.capacity = capacity
15+
self.dict = dict()
16+
self.head = Node(0, 0)
17+
self.tail = Node(0, 0)
18+
self.head.next = self.tail
19+
self.tail.prev = self.head
20+
21+
def remove(self, node):
22+
prev = node.prev
23+
next = node.next
24+
prev.next = next
25+
next.prev = prev
26+
27+
def add(self, node):
28+
prev = self.tail.prev
29+
prev.next = node
30+
self.tail.prev = node
31+
node.prev = prev
32+
node.next = self.tail
33+
34+
def get(self, key):
35+
"""
36+
:type key: int
37+
:rtype: int
38+
"""
39+
if key in self.dict:
40+
node = self.dict[key]
41+
self.remove(node)
42+
self.add(node)
43+
return node.value
44+
return -1
45+
46+
47+
def put(self, key, value):
48+
"""
49+
:type key: int
50+
:type value: int
51+
:rtype: void
52+
"""
53+
if key in self.dict:
54+
self.remove(self.dict[key])
55+
node = Node(key, value)
56+
self.add(node)
57+
self.dict[key] = node
58+
if len(self.dict) > self.capacity:
59+
node = self.head.next
60+
self.remove(node)
61+
del self.dict[node.key]

test_for_lru_cache.py

+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
from lru_cache import *
2+
3+
# Your LRUCache object will be instantiated and called as such:
4+
# obj = LRUCache(capacity)
5+
# param_1 = obj.get(key)
6+
# obj.put(key,value)

0 commit comments

Comments
 (0)