ProgrammingVery hardTCS CodeVita · Infosys HackWithInfy
What is printed?
What is printed?
import heapq
h = []
try:
heapq.heappush(h, (1, {'a': 1}))
heapq.heappush(h, (1, {'b': 2}))
except TypeError as e:
print(type(e).__name__)
print(len(h))- A. TypeError 2
- B. TypeError 1
- C. ValueError 2
- D. No output 2
Correct answer: A. TypeError 2
The second push compares (1, {'b': 2}) with (1, {'a': 1}). The first fields tie, so Python compares the dicts, which do not support <. heappush appends the new item before it sifts up, so the failed comparison still leaves the heap with 2 items.
More Python Programming questions
- What is printed? python import heapq print(heapq.nlargest(2, ['pear', 'fig', 'apple'], key=len))
- What is printed? python import heapq h = [] for t in [(2, 'b'), (2, 'a'), (1, 'z')]: heapq.heappush(h, t) print([heapq.heappop(h) for in…
- 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…