Predict the output
Capacity 2. After put a, put b, get a, put c, which keys remain?
from collections import OrderedDict
class LRU:
def __init__(self, capacity: int) -> None:
self.cap = capacity
self.data: OrderedDict[str, str] = OrderedDict()
def get(self, key: str) -> str | None:
if key not in self.data:
return None
self.data.move_to_end(key)
return self.data[key]
def put(self, key: str, value: str) -> None:
self.data[key] = value
self.data.move_to_end(key)
if len(self.data) > self.cap:
self.data.popitem(last=False)
c = LRU(2)
c.put("a", "1")
c.put("b", "2")
c.get("a")
c.put("c", "3")
print(list(c.data))Hint 1 of 1
Which key was touched least recently?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: A ['a', 'c']
Correct. Reading a made b the least recently used, so b was evicted.
LRU evicts the entry that was used longest ago. The get moved a to the most-recent end, so when c pushed the cache past 2 entries, b was the oldest and went.
Why not the others?
- B
['b', 'c']. a was used more recently than b. - C
['a', 'b']. Adding c over capacity evicts one key. - D
['a', 'b', 'c']. Capacity is 2.