Python-based minimum priority queue code sharing

Source: Internet
Author: User

Copy codeThe Code is as follows:
#-*-Coding: UTF-8 -*-

Class Heap (object ):

@ Classmethod
Def parent (cls, I ):
"Parent subscripts """
Return int (I-1)> 1 );

@ Classmethod
Def left (cls, I ):
"Left son subscript """
Return (I <1) + 1;

@ Classmethod
Def right (cls, I ):
"Right son subscript """
Return (I <1) + 2;

Class MinPriorityQueue (list, Heap ):

@ Classmethod
Def min_heapify (cls, A, I, heap_size ):
"Minimum heap A [I] is the root subtree """
L, r = cls. left (I), cls. right (I)
If l Least = l
Else:
Least = I
If r Least = r
If least! = I:
A [I], A [least] = A [least], A [I]
Cls. min_heapify (A, least, heap_size)

Def minimum (self ):
"Returns the smallest element. The pseudo code is as follows:
HEAP-MINIMUM ()
1 return A [1]

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

Def extract_min (self ):
"Removes and returns the smallest element. The pseudo code is as follows:
HEAP-EXTRACT-MIN)
1 if heap-size [A] <1
2 then error "heap underflow"
3 min minutes A [1]
4 A [1] specify A [heap-size [A] // place the end element first.
5 heap-size [A] ← heap-size [A]-1 // reduce heap-size [A]
6 MIN-HEAPIFY (A, 1) // keep minimum heap Properties
7 return min

T (n) = θ (lgn)
"""
Heap_size = len (self)
Assert heap_size> 0, "heap underflow"
Val = self [0]
Tail = heap_size-1
Self [0] = self [tail]
Self. min_heapify (self, 0, tail)
Self. pop (tail)
Return val

Def decrease_key (self, I, key ):
"Reduces the I value to the key. The pseudo code is as follows:
HEAP-DECREASE-KEY (A, I, key)
1 if key> A [I]
2 then error "new key is larger than current key"
3 A [I] primary key
4 while I> 1 and A [PARENT (I)]> A [I] // when the PARENT node is larger than the root node
5 do exchange A [I]↔A [PARENT (I)] // exchange two elements
6 I usually PARENT (I) // point to the PARENT node location

T (n) = θ (lgn)
"""
Val = self [I]
Assert key <= val, "new key is larger than current key"
Self [I] = key
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 ):
"Inserts the key into A. the pseudo code is as follows:
MIN-HEAP-INSERT (A, key)
1 heap-size [A] ← heap-size [A] + 1 // increase in the number of elements
2 A [heap-size [A] Starting + ∞ // the newly added element is + ∞.
3 HEAP-DECREASE-KEY (A, heap-size [A], key) // reduce the number of new elements to the key

T (n) = θ (lgn)
"""
Self. append (float ('inf '))
Self. decrease_key (len (self)-1, key)

If _ name _ = '_ main __':
Import random

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

Queue = MinPriorityQueue () # insert mode to create the minimum heap
For I in keys:
Queue. insert (I)
Print (queue)

Print ('* 30)

For I in range (len (queue )):
Val = I % 3
If val = 0:
Val = queue. extract_min () # Remove and return the minimum element
Elif val = 1:
Val = queue. minimum () # returns the smallest element.
Else:
Val = queue [1]-10
Queue. decrease_key (1, val) # reduce queue [1] by 10
Print (queue, val)

Print ([queue. extract_min () 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.