ProgrammingHardTCS CodeVita · Infosys HackWithInfy
What is printed?
What is printed?
import heapq
class T:
def __init__(self, p, n):
self.p = p
self.n = n
def __lt__(self, o):
return self.p > o.p
h = []
for p, n in [(1, 'a'), (3, 'b'), (2, 'c')]:
heapq.heappush(h, T(p, n))
print(heapq.heappop(h).n)- A. b
- B. a
- C. c
- D. TypeError
Correct answer: A. b
heapq only uses __lt__, and this one is reversed, so the heap is a max-heap on p. The smallest 'less-than' element is the one with the largest priority, which is b with p = 3.
More Python Programming questions
- What is printed? python class P: def init(self, x): self.x = x def eq(self, o): return self.x == o.x try: print(len({P(1)})) except…
- What is printed? python from functools import reduce print(reduce(lambda a, b: a b, range(1, 21), 1), reduce(lambda a, b: a + b, [], 0))
- What is printed? python try: print(sorted([3, None, 1])) except TypeError as e: print(e)
- What is printed? python def flat(x): for y in x: if isinstance(y, list): yield from flat(y) else: yield y print(list(flat([1, [2, [3…
- What is printed? python print(len(str(int('7' 4300)))) try: int('7' 4301) except ValueError: print('no')
- What is printed? python print(round(0.25, 1), round(0.35, 1), round(2.5), round(-0.5))