Skip to content
Open
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@
node_modules
.venv
__pycache__
package-lock.json
50 changes: 50 additions & 0 deletions Sprint-2/implement_lru_cache/lru_cache.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import time
Comment thread
katarzynakaz marked this conversation as resolved.
Outdated
Comment thread
katarzynakaz marked this conversation as resolved.
Outdated
from collections import OrderedDict

class LruCache:
# `LruCache(limit)` should construct
# an LRU cache which never stores more than `limit` entries.
def __init__(self, user_limit):
self.limit = user_limit
self.our_list = OrderedDict()
Comment thread
katarzynakaz marked this conversation as resolved.
Outdated
self.lookup_map = {}
Comment thread
katarzynakaz marked this conversation as resolved.
Outdated

# * `set(key, value)` should associate `value` with the passed `key`.
def set(self, key, value):

if key in self.lookup_map:
old_item = self.lookup_map[key]
self.our_list.pop(key)
wrapped_item = {
"key": key,
"value": value,
}

#add to list and map
self.our_list[key] = wrapped_item
Comment thread
katarzynakaz marked this conversation as resolved.
Outdated
self.our_list.move_to_end(key, last=False)
self.lookup_map[key] = wrapped_item

#if full remove oldest timestamp so last
if len(self.our_list) > self.limit:
# oldest_item = self.our_list.pop()

# del self.lookup_map[oldest_item["key"]]
oldest_key, oldest_item = self.our_list.popitem()
del self.lookup_map[oldest_key]

# * `get(key)` should look-up the value previously associated with `key`.
def get(self, key):
#check map instead of for loop
if key in self.lookup_map:
# find by key
item = self.lookup_map[key]

#move to front
# self.our_list.remove(item)
# self.our_list.insert(0, item)
self.our_list.move_to_end(key, last=False)

return item["value"]
return None