ProgrammingVery hardProduct company OA
What is printed?
What is printed?
import heapq
tasks = [(2, "write"), (1, "test"), (2, "ship"), (1, "plan")]
h = []
for i, (p, name) in enumerate(tasks):
heapq.heappush(h, (p, -i, name))
order = [heapq.heappop(h)[2] for _ in range(3)]
print(order, h[0][2], heapq.nsmallest(2, tasks)[1])- A. ['test', 'plan', 'write'] ship (1, 'test')
- B. ['plan', 'test', 'write'] ship (1, 'test')
- C. ['plan', 'test', 'ship'] write (2, 'ship')
- D. ['plan', 'test', 'ship'] write (1, 'test')
Correct answer: D. ['plan', 'test', 'ship'] write (1, 'test')
Tuples compare element by element, so among equal priorities the second field decides. It is −i, which makes the LATER-inserted task smaller: (1, −3, plan) < (1, −1, test) < (2, −2, ship) < (2, 0, write). Three pops give plan, test, ship and 'write' remains. nsmallest on the raw (priority, name) tuples breaks the tie alphabetically: (1, 'plan'), (1, 'test'). Using +i as the tie-breaker would give the FIFO order test, plan, write.
More Python Programming questions
- What is printed? python x = -13 print(x >> 2, x // 4, ~x, x & 0xF, bin(x & 0xFF).count("1"), (-x) >> 2)
- What is printed? python def chain(nums, divisors): g = (n for n in nums) for d in divisors: g = (n for n in g if n % d) return list(g)…
- What is printed? python class V: def init(self, n, log): self.n, self.log = n, log def add(self, o): self.log.append("add"); return…
- What is printed? python log = [] def t(x): log.append(x); return x def f(a, b=t("d1"), args, c=t("d2"), kw): return a, b, args, c…
- What is printed? python d = dict.fromkeys("ab", []) d["a"].append(1) d["b"] = d["b"] + [2] d["a"] += [3] g = [[]] 2 + [[] for in range(2)]…
- A log pipeline must remove duplicate event ids from a list xs of n = 2·10⁵ integers while keeping the order of first occurrence. Four…