Skip to content

Commit a1302d3

Browse files
committed
lru cache task completed
1 parent e718fb4 commit a1302d3

1 file changed

Lines changed: 102 additions & 0 deletions

File tree

Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
import time
2+
3+
our_list = []
4+
lookup_map = {}
5+
limit = 0
6+
7+
# `LruCache(limit)` should construct
8+
# an LRU cache which never stores more than `limit` entries.
9+
def LruCache(user_limit):
10+
global limit, our_list, lookup_map
11+
limit = user_limit
12+
our_list = []
13+
lookup_map = {}
14+
15+
# * `set(key, value)` should associate `value` with the passed `key`.
16+
def set(key, value):
17+
global our_list, lookup_map
18+
19+
if key in lookup_map:
20+
old_item = lookup_map[key]
21+
our_list.remove(old_item)
22+
23+
wrapped_item = {
24+
"key": key,
25+
"value": value,
26+
"tracker": time.time()
27+
}
28+
29+
#add to list and map
30+
our_list.insert(0, wrapped_item)
31+
lookup_map[key] = wrapped_item
32+
33+
#if full remove oldest timestamp so last
34+
if len(our_list) > limit:
35+
oldest_item = our_list.pop()
36+
37+
del lookup_map[oldest_item["key"]]
38+
39+
40+
# * `get(key)` should look-up the value previously associated with `key`.
41+
def get(key):
42+
global our_list, lookup_map
43+
#check map instead of for loop
44+
if key in lookup_map:
45+
# find by key
46+
item = lookup_map[key]
47+
48+
# // tracker to now timestamp updaed
49+
item["tracker"] = time.time()
50+
51+
#to front
52+
our_list.remove(item)
53+
our_list.insert(0, item)
54+
55+
return item["value"]
56+
57+
return None
58+
59+
60+
#before i did it this was but was looping over each item and did not
61+
#fit the required complexity
62+
# def get_old(key):
63+
# for item in our_list:
64+
# if item["key"] == key:
65+
# item["tracker"] = time.time()
66+
# our_list.remove(item)
67+
# our_list.insert(0, item)
68+
# return item["value"]
69+
# return None
70+
71+
#and before tried with an id not timestamp
72+
# tracker_number = 0
73+
74+
# def set(key, value):
75+
# global tracker_number, our_list, lookup_map
76+
77+
78+
# wrapped_item = {
79+
# "key": key,
80+
# "value": value,
81+
# "tracker": tracker_number
82+
# }
83+
84+
85+
# tracker_number += 1
86+
87+
# our_list.insert(0, wrapped_item)
88+
# lookup_map[key] = wrapped_item
89+
90+
# and the loop
91+
# def get_old(key):
92+
# global tracker_number, our_list
93+
# for item in our_list:
94+
# if item["key"] == key:
95+
# item["tracker"] = tracker_number
96+
# tracker_number += 1
97+
98+
# our_list.remove(item)
99+
# our_list.insert(0, item)
100+
101+
# return item["value"]
102+
# return None

0 commit comments

Comments
 (0)