انتقل للمحتوى
Robo EgyptRobo Egypt
تقدّمك في الجزء0 من 21
الدرس 6.2 · الكود والأرقام⏱ 12 دقيقة
الفصل 6: Heaps و Priority Queues

تجربة: heap بإيدك و heapq

بنينا heap بالـ push والـ pop، وبعدين جرّبنا heapq.

  • heapq مكتوبة بـ C وأسرع.
  • min-heap بس: للـ max حط القيم بالسالب.
  • أكبر 3 من مليون رقم: heap صغير بـ 3 عناصر بدل ما ترتب الكل.

الشرح بالتفصيل

class MinHeap:
    def __init__(self):
        self.a = []

    def push(self, x):                        # O(log n)
        a = self.a
        a.append(x)
        i = len(a) - 1
        while i > 0 and a[(i - 1) // 2] > a[i]:     # sift up
            p = (i - 1) // 2
            a[i], a[p] = a[p], a[i]
            i = p

    def pop(self):                            # O(log n)
        a = self.a
        a[0], a[-1] = a[-1], a[0]
        top = a.pop()
        i = 0
        while True:                           # sift down
            l, r, s = 2 * i + 1, 2 * i + 2, i
            if l < len(a) and a[l] < a[s]: s = l
            if r < len(a) and a[r] < a[s]: s = r
            if s == i:
                return top
            a[i], a[s] = a[s], a[i]
            i = s

    def __len__(self):
        return len(self.a)

h = MinHeap()
for x in [5, 3, 8, 1, 9, 2]:
    h.push(x)
print(h.a)                                    # [1, 3, 2, 5, 9, 8]  ← شكل 3.8
print([h.pop() for _ in range(len(h))])       # [1, 2, 3, 5, 8, 9]  ← Heap Sort!

في الشغل الحقيقي استخدم heapq المدمجة (مكتوبة بـ C). خلي بالك إنها min-heap بس، فلو عايز max-heap حط القيم بالسالب.

ملاحظةheapq.nlargest(k, data) بتعملها في سطر.
خلصت الدرس؟ علّم عليه عشان تقدّمك يتحسب.