ProgrammingHardTCS CodeVita · Infosys HackWithInfy
What is printed?
What is printed?
import heapq
h = []
for t in [(2, 'b'), (2, 'a'), (1, 'z')]:
heapq.heappush(h, t)
print([heapq.heappop(h) for _ in range(3)])- A. [(2, 'a'), (2, 'b'), (1, 'z')]
- B. [(2, 'b'), (2, 'a'), (1, 'z')]
- C. [(1, 'z'), (2, 'a'), (2, 'b')]
- D. [(1, 'z'), (2, 'b'), (2, 'a')]
Correct answer: C. [(1, 'z'), (2, 'a'), (2, 'b')]
Tuples compare field by field, so the heap pops (1, 'z') first and then breaks the tie of 2 with the string 'a' before 'b'.
More Python Programming questions
- What is printed? python import heapq print(heapq.nsmallest(3, [3, 1, 3, 2], key=lambda x: -x))
- Dijkstra's algorithm with heapq has no decrease-key operation. Which approach is the standard one in Python?
- A program inserts n = 200000 items one at a time with lst.insert(0, x) and never removes them. Which is the time complexity of the whole…
- A solution does if x not in seenlist for each of n = 2 10^5 values, where seenlist grows to n items. Which change gives the best speedup…
- What is printed? python import heapq print(heapq.nsmallest(0, [5, 1]), max([], default=-1), min([3, 1, 2], key=lambda x: -x))
- What is printed? python print(pow(2, -1, 10 9 + 7))