Python calculates the maximum priority queue instance _python

Source: Internet
Author: User

Copy Code code as follows:

#-*-Coding:utf-8-*-

Class Heap (object):

@classmethod
def parent (CLS, i):
"" "Parent node Subscript" "
return int ((i-1) >> 1);

@classmethod
Def left (CLS, i):
"" "" "The Left son subscript" "
Return (I << 1) + 1;

@classmethod
def right (CLS, i):
"" "the Right son subscript" "
Return (I << 1) + 2;

Class Maxpriorityqueue (list, Heap):

    @classmethod
    def max_heapify (CLS, A, I, heap_size):
         "" Max Heap A[i] is the root subtree "" "
        l, r = Cls.left (i) , Cls.right (i)
        if L < heap_size and a[l] > A[i]:
  & nbsp;         largest = L
        Else:
            largest = i
         if R < heap_size and A[r] > A[largest]:
       & nbsp;    largest = r
        If largest!= i:
             A[i], a[largest] = A[largest], a[i]
             cls.max_heapify (A, largest, heap_size)

def maximum (self):
"" Returns the maximum element, the pseudo code is as follows:
Heap-maximum (S)
1 return a[1]

T (n) = O (1)
"""
return self[0]

    def Extract_max (self):
        "" To remove and return the largest element, the pseudo code is as follows:
        Heap-extract-max (A)
        1   If HEAP-SIZE[A] < 1
        2    then error heap Underflow "
        3  max←a[1]
         4  A[1]←a[heap-size[a]]//tail element to first
        5  Heap-size[a]←heap-size[a]-1//decrease Heap-size[a]
        6  max-heapify (A, 1///Maintain maximum heap properties
        7  return max

        T (n) =θ (LGN)
        ""
        heap_size = Len (self)
        Assert heap_size > 0, "Heap underflow"
        val = self[0]
  & nbsp;     tail = heap_size-1
        self[0] = Self[tail]
        self.max_heapify (self, 0, tail)
         self.pop (tail)
        return Val

    def increase_key (self, I, key):
        "" adds the value of I to the key, The pseudo code is as follows:
        Heap-increase-key (A, I, KEY)
         1  if key < A[i]
        2    the Error "New key is smaller than current key"
        3  a[i]←key
 &nb sp;      4  While I > 1 and a[parent (i)] < A[i]//not root node and parent node more hours
         5    do Exchange a[i]↔a[parent (i)]//Exchange two element
         6       i←parent (i)//point to parent node location

        T (n) =θ (LGN)
        ""
        val = self[i]
        assert key >= Val, "New key is smaller than current key"
        self[i] = key
 &nb sp;      parent = self.parent
        while i > 0 and Self[parent (i)] < Self[i]:
            self[i], Self[parent (i)] = Self[parent (i)], self[i]
            i = parent (i)

def insert (self, key):
"" To insert a key, the pseudo code is as follows:
Max-heap-insert (A, key)
1 Heap-size[a]←heap-size[a] + 1//Increased number of elements
2 a[heap-size[a]]←-∞//Initial new addition element is-∞
3 Heap-increase-key (A, Heap-size[a], key)//Add new elements to key

T (n) =θ (LGN)
"""
Self.append (Float ('-inf '))
Self.increase_key (Len (self)-1, key)

if __name__ = = ' __main__ ':
Import Random

Keys = Range (10)
Random.shuffle (keys)
Print (keys)

Queue = Maxpriorityqueue () # Insert Way Build Max Heap
For i in the keys:
Queue.insert (i)
Print (queue)

Print (' * ' * 30)

For I in range (Len (keys)):
val = i% 3
If val = 0:
val = Queue.extract_max () # Remove and return the largest element
Elif val = = 1:
val = queue.maximum () # returns the largest element
Else
val = queue[1] + 10
Queue.increase_key (1, Val) # Queue[1] increase by 10
Print (queue, Val)

Print ([Queue.extract_max () for I in range (len (queue))]

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.