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)]))
  1. A. [10, 20, 30]
  2. B. [-1, 10, 30]
  3. C. [10, -1, -1]
  4. 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

Exams that ask this topic