[Py3]--heap module and heap sequencing

Source: Internet
Author: User
Tags iterable

Heapify ()

The Heapify () function is used to convert a sequence into an initialized heap

 nums=[16,7,3,20,17,8,-1  print  ( Span style= "color: #800000;" > '  

Heappush ()

Heappush () is an operation that implements inserting elements into the heap
Be sure to initialize the sequence before the Heappush () operation! Heappush is for the "heap" Operation! Otherwise, it doesn't make sense.

Nums=[16,7,3,20,17,8,-1]print(nums) show_tree (nums)       [7, 3, 8, 1]                                              7                 3       8        -1     ------------------------------------

Heapq.heapify (nums)print (' initialize heap:', nums) show_tree (nums) Initialize piles: [-1, 7, 3, 8, +, +]- 1 7 3 8------------------------------------     
 forIinchRandom.sample (Range (1,8), 2):    Print("This push:", i) Heapq.heappush (nums,i)Print(nums) show_tree (nums) This push:5    [-1, 5, 3, 7, 17, 8, 16, 20]                     -1 5 3 7 8----------- -------------------------This push:7    [-1, 5, 3, 7, 17, 8, 16, 20, 7]                     -1 5 3 7 (8) 7------- -----------------------------

Heappop ()

Heappop () is an operation that implements removing an element out of a heap
Be sure to initialize the sequence before the same operation, otherwise it doesn't make sense.

Nums=[16,7,3,20,17,8,-1]print(nums) show_tree (nums)          [7, 3, 8, 1]                                                      7                 3       8        -1         ------------------------------------heapq.heapify ( nums)print(' Initialize heap:', Nums) show_tree (nums)        initialize piles: [ -1, 7, 3, 1, 8, +                         ]-7                                 3 8                 -           ---------------------- --------------
 forIinchRange (0,2):    Print("this time pop:", Heapq.heappop (nums))Print(nums) show_tree (nums) This pop:-1        [3, 7, 8, 20, 17, 16]                         3 7 8---------------- --------------------this time pop:3        [7, 16, 8, 20, 17]                         7 8------------------------- -----------
Nlargest ()/nsmallest ()

Sorted (iterable, Key=key, reverse=true) [: n]

    • Nlargest (n,iterable) to find TOPN in sequence iterable | Nsmallest (n,iterable) to find BTMN in sequence iterable
Import heapqnums=[16,7,3,20,17,8,-1]print(heapq.nlargest (3, nums))print( Heapq.nsmallest (3, nums)) [1, 3, 7]
    • Nlargest (n, iterable, KEY=LAMBDA) | Nsmallest (n, iterable, KEY=LAMBDA) key accepts the keyword parameter for use in more complex data structures
defPrint_price (dirt): forIinchDirt: forX, yinchI.items ():ifx==' Price':                Print(x, y) portfolio= [    {'name':'IBM','shares': 100,' Price': 91.1},    {'name':'AAPL','shares': 50,' Price': 543.22},    {'name':'FB','shares': 200,' Price': 21.09},    {'name':'HPQ','shares': 35,' Price': 31.75},    {'name':'YHOO','shares': 45,' Price': 16.35},    {'name':'ACME','shares': 75,' Price': 115.65}]cheap=heapq.nsmallest (3,portfolio,key=Lambdax:x[' Price']) Expensive=heapq.nlargest (3,portfolio,key=Lambday:y[' Price']) print_price (cheap) print_price (expensive) price16.35 Price21.09 Price31.75 Price543.22 Price115.65 Price91.1

About the heap and heap sort

For the nums=[16,7,3,20,17,8,-1] sequence above, the diagram illustrates:

Constructing the heap operations (click to view)

Push heap operations (click to view)

Operation of the Pop heap (click to view)

Reference Articles

Details of the use of the HEAPQ module in Python (including Show_tree ())

Detailed heap Sequencing

Discussion on algorithm and data structure: five-priority queue and heap sort

[Py3]--heap module and heap sequencing

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.