krahets/hello-algo · error · IndexError

堆積為空

Error message

堆積為空

What it means

Raised by the pop() method of a max-heap when attempting to extract the root element from a heap with zero nodes. The method first checks is_empty() (which compares size() to 0), then swaps the root with the last leaf, removes it, and sifts down. Unlike peek() which accesses max_heap[0] without a guard, pop() has explicit emptiness protection.

Source

Thrown at zh-hant/codes/python/chapter_heap/my_heap.py:77

    def sift_up(self, i: int):
        """從節點 i 開始,從底至頂堆積化"""
        while True:
            # 獲取節點 i 的父節點
            p = self.parent(i)
            # 當“越過根節點”或“節點無須修復”時,結束堆積化
            if p < 0 or self.max_heap[i] <= self.max_heap[p]:
                break
            # 交換兩節點
            self.swap(i, p)
            # 迴圈向上堆積化
            i = p

    def pop(self) -> int:
        """元素出堆積"""
        # 判空處理
        if self.is_empty():
            raise IndexError("堆積為空")
        # 交換根節點與最右葉節點(交換首元素與尾元素)
        self.swap(0, self.size() - 1)
        # 刪除節點
        val = self.max_heap.pop()
        # 從頂至底堆積化
        self.sift_down(0)
        # 返回堆積頂元素
        return val

    def sift_down(self, i: int):
        """從節點 i 開始,從頂至底堆積化"""
        while True:
            # 判斷節點 i, l, r 中值最大的節點,記為 ma
            l, r, ma = self.left(i), self.right(i), i
            if l < self.size() and self.max_heap[l] > self.max_heap[ma]:
                ma = l
            if r < self.size() and self.max_heap[r] > self.max_heap[ma]:
                ma = r

View on GitHub (pinned to 69932aed18)

Solutions

  1. Check heap.is_empty() before calling pop()
  2. Use heap.size() as the loop bound when draining all elements
  3. Wrap in try/except IndexError for defensive extraction

Example fix

# before
val = heap.pop()

# after
if not heap.is_empty():
    val = heap.pop()
else:
    val = None
Defensive patterns

Strategy: validation

Validate before calling

if not heap.is_empty():
    val = heap.pop()
else:
    val = None

Try / catch

try:
    val = heap.pop()
except IndexError:
    val = None

Prevention

When it happens

Trigger: Calling heap.pop() on a MaxHeap constructed from an empty list; draining all elements with repeated pop() and then calling pop() once more; constructing MaxHeap([]) and immediately extracting.

Common situations: Priority-queue consumers that process all items and then attempt one more pop; heap-sort implementations that pop exactly n+1 times; testing with empty input arrays.

Related errors


AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13). Data as JSON: /api/errors/38f05d64e3814e32. Report an issue: GitHub.