|
1 | | -import time |
2 | 1 | from collections import OrderedDict |
3 | 2 |
|
4 | 3 | class LruCache: |
5 | | - # `LruCache(limit)` should construct |
| 4 | + # TASK |
| 5 | + # `LruCache(limit)` should construct |
6 | 6 | # an LRU cache which never stores more than `limit` entries. |
7 | 7 | def __init__(self, user_limit): |
8 | 8 | self.limit = user_limit |
9 | | - self.our_list = OrderedDict() |
10 | | - self.lookup_map = {} |
| 9 | + self.our_key_dictionary = OrderedDict() |
11 | 10 |
|
12 | | - # * `set(key, value)` should associate `value` with the passed `key`. |
| 11 | + # TASK |
| 12 | + # `set(key, value)` should associate `value` with the passed `key`. |
13 | 13 | def set(self, key, value): |
14 | 14 |
|
15 | 15 | if key in self.lookup_map: |
16 | 16 | old_item = self.lookup_map[key] |
17 | | - self.our_list.pop(key) |
| 17 | + self.our_key_dictionary.pop(key) |
18 | 18 | wrapped_item = { |
19 | 19 | "key": key, |
20 | 20 | "value": value, |
21 | 21 | } |
22 | 22 |
|
23 | | - #add to list and map |
24 | | - self.our_list[key] = wrapped_item |
25 | | - self.our_list.move_to_end(key, last=False) |
26 | | - self.lookup_map[key] = wrapped_item |
| 23 | + self.our_key_dictionary[key] = wrapped_item |
| 24 | + self.our_key_dictionary.move_to_end(key, last=False) |
27 | 25 |
|
28 | | - #if full remove oldest timestamp so last |
29 | | - if len(self.our_list) > self.limit: |
30 | | - # oldest_item = self.our_list.pop() |
31 | | - |
32 | | - # del self.lookup_map[oldest_item["key"]] |
33 | | - oldest_key, oldest_item = self.our_list.popitem() |
34 | | - del self.lookup_map[oldest_key] |
| 26 | + if len(self.our_key_dictionary) > self.limit: |
| 27 | + self.our_key_dictionary.popitem() |
35 | 28 |
|
36 | | - # * `get(key)` should look-up the value previously associated with `key`. |
37 | 29 | def get(self, key): |
38 | | - #check map instead of for loop |
39 | | - if key in self.lookup_map: |
40 | | - # find by key |
41 | | - item = self.lookup_map[key] |
42 | | - |
43 | | - #move to front |
44 | | - # self.our_list.remove(item) |
45 | | - # self.our_list.insert(0, item) |
46 | | - self.our_list.move_to_end(key, last=False) |
47 | | - |
| 30 | + if key in self.our_key_dictionary: |
| 31 | + item = self.our_key_dictionary[key] |
| 32 | + self.our_key_dictionary.move_to_end(key, last=False) |
| 33 | + |
48 | 34 | return item["value"] |
49 | 35 | return None |
50 | 36 |
|
0 commit comments