Python implementation Priority Queue (II)

Source: Internet
Author: User

After the heap is built, we only need to return the first element of the array, that is, the minimum value can be taken.

    def Peek (self):                                return Self._elems[0]

After that, you need to insert elements and delete elements.

Deleting elements and building a heap is a bit similar, ejecting the element you want to delete from the top of the heap, then taking the last element out and re-building the heap to get a new minimum heap:

    def dequeue (self):         = Self._elems        = Elems[0]        = elems.pop ()        if len (elems) > 0:            self.siftdown (E, 0, Len (elems))        return E0

Inserting elements is slightly different, inserting elements is inserting elements from the last position and then scanning up, if smaller than the sibling node or parent node, swapping locations, otherwise finding the location, which is the opposite of a downward scan:

    def Siftup (self, E, last):         = Self._elems, Last, (last-1)//2 and         e < elems[j]:            = Elems[j]            = j, (j-1)//2        = E

Insert a new element because the total number of elements increases, so first with a none to the new added elements to occupy a position, the last method is:

    def Enqueue (Self, e):        self._elems.append (None)        Self.siftup (E, Len (self._elems)-1)         return self._elems

In this way, a priority queue is implemented

Python implementation Priority Queue (II)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.