ProgrammingVery hardCognizant GenC · TCS NQT
What is printed?
What is printed?
def lru(cap, ops):
d = {}
out = []
for op, k in ops:
if op == 'get':
if k in d:
v = d.pop(k)
d[k] = v
out.append(v)
else:
out.append(-1)
else:
if k in d:
d.pop(k)
elif len(d) == cap:
d.pop(next(iter(d)))
d[k] = k * 10
return out
print(lru(2, [('put', 1), ('put', 2), ('get', 1), ('put', 3), ('get', 2), ('get', 3)]))- A. [10, 20, 30]
- B. [-1, 10, 30]
- C. [10, -1, -1]
- D. [10, -1, 30]
Correct answer: D. [10, -1, 30]
A dict keeps insertion order, so a get moves its key to the end by popping and reinserting it. Key 2 is the least recently used when key 3 arrives, so it is evicted and get(2) returns -1.
More Python Programming questions
- What is printed? python from itertools import combinations a = [1, 2, 3, 4] cnt = 0 for r in range(1, len(a) + 1): for c in…
- What is printed? python from collections import Counter def pairseq(a, t): c = Counter(a) total = 0 for x in c: y = t - x if x < y: total…
- What is printed? python import bisect def minlen(a, s): pre = [0] for x in a: pre.append(pre[-1] + x) best = float('inf') for i in…
- What is printed? python people = [('Ann', 30), ('Bob', 25), ('Cid', 30), ('Dan', 25)] s1 = sorted(people, key=lambda p: p[0]) s2 =…
- What is printed? python from itertools import accumulate h = [3, 1, 4, 1, 5, 9, 2, 6] vis = [x for x, m in zip(h, [0] + list(accumulate(h…
- For an array of 10^6 numbers, which approach finds the largest sum of k consecutive elements fastest and correctly?