LearnFrenzy
Sign in Take a free test

Python Coding Interview Questions · Find the Bug · Question 5

Bug: "top 3 scores" are the lowest Answer, explanation & discussion

  • Find the error
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 5 Back to Exercise

The program should print the three highest scores. Which statement correctly identifies the bug?

main.py
import heapq
scores = [72, 95, 58, 88, 64, 91]
heap = scores[:]
heapq.heapify(heap)
print([heapq.heappop(heap) for _ in range(3)])
  • A heapify sorts in descending order
  • B scores[:] creates the wrong list
  • C heapq is a min-heap, so pops return the smallest values; use heapq.nlargest(3, scores) or push negated values Correct
  • D heappop removes random items
Correct Answer: Option C

Remember heapq always keeps the smallest item at index 0.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links