Usage of the HEAPQ module in Python

Source: Internet
Author: User
The HEAPQ module provides a heap algorithm. HEAPQ is a tree-shaped data structure that sorts child nodes and parent nodes. This module provides HEAP[K] <= heap[2*k+1] and Heap[k] <= heap[2*k+2]. In order to compare the non-existent elements are infinitely large. The smallest element of the heap is always [0].

Print HEAPQ Type

Import Math Import randomfrom Cstringio import stringiodef show_tree (tree, total_width=36, fill= "):   output = Stringi O ()   Last_row = 1   for I, N in Enumerate (tree):     If I:       row = Int (Math.floor (Math.log (i+1, 2)))     else:< C7/>row = 0     if row! = Last_row:       output.write (' \ n ')     columns = 2**row     col_width = Int (Math.floor (total _width * 1.0)/columns))     output.write (str (n). Center (col_width, fill))     Last_row = row   Print Output.getvalue ()   print '-' * total_width   print    returndata = random.sample (range (1,8), 7) print ' Data: ' , Datashow_tree (data)

Print results

Data: [3, 2, 6, 5, 4, 7, 1]     3             2      6      5    4  7     1   -------------------------Heapq.heappush ( Heap, item)

Push an element into the heap, modify the code above

heap = []data = random.sample (range (1,8), 7) print ' Data: ', datafor i in data:  print ' Add%3d: '% i  heapq.heappush (Heap, I)  Show_tree (Heap)

Print results

Data: [6, 1, 5, 4, 3, 7, 2]add  6:         6          ------------------------------------add  1:      1    6         ------ ------------------------------Add  5:      1    6       5       ------------------------------------Add  4:        1     4       5         6------------------------------------add  3:        1     3       5         6    4------------------------------------Add  7:        1     3        5         6    4    7-------------- ----------------------Add  2:        1     3        2         6    4    7    5---------------------------- --------

Depending on the result, the element of the child node is greater than the parent element. The sibling nodes are not sorted.

Heapq.heapify (list)

Converts the list type to heap, and rearranges the lists within linear time.

print ' data: ', dataheapq.heapify (data) print ' data: ', Datashow_tree (data)

Print results

Data: [2, 7, 4, 3, 6, 5, 1]data: [1, 3, 2, 7, 6, 5, 4]      1            3         2     7    6    5    4  --------------------- ---------------Heapq.heappop (Heap)

Deletes and returns the smallest element in the heap, sorted by Heapify () and Heappop ().

data = Random.sample (range (1, 8), 7) print ' Data: ', dataheapq.heapify (data) show_tree (data) heap = []while data:  i = Hea Pq.heappop (data)  print ' pop%3d: '% i  show_tree (data)  heap.append (i) print ' heap: ', heap

Print results

Data: [4, 1, 3, 7, 5, 6, 2]         1    4         2  7    5    6    3------------------------------------pop  1:         2    4         3  7    5    6------------------------------------pop  2:         3    4         6  7    5------------------------------------pop  3:         4    5         6  7--------------------- ---------------Pop  4:         5    7         6------------------------------------pop  5:         6    7-- ----------------------------------Pop  6:        7------------------------------------pop  7:----------- -------------------------heap: [1, 2, 3, 4, 5, 6, 7]

You can see the sorted heap.

Heapq.heapreplace (iterable, N)

Delete the existing element and replace it with a new value.

data = Random.sample (range (1, 8), 7) print ' Data: ', dataheapq.heapify (data) show_tree (data) for n in [8, 9, ten]:  smalles t = heapq.heapreplace (data, N)  print ' Replace%2d with%2d: '% (smallest, n)  show_tree (data)

Print results

Data: [7, 5, 4, 2, 6, 3, 1]         1    2         3  5    6    7    4------------------------------------replace 1 with 8:         2    5         3  8    6    7    4------------------------------------replace 2 with 9:         3    5         4  8    6    7    9------------------------------------replace 3 with:         4    5         7  8    6    9------------------------------------

Heapq.nlargest (n, iterable) and Heapq.nsmallest (n, iterable)

Returns n maximum and minimum values in a list

data = Range (1,6) L = heapq.nlargest (3, data) print L     # [5, 4, 3]s = Heapq.nsmallest (3, data) print S     # [1, 2, 3]

PS: A computational problem
Build the smallest heap code instance with the number of elements k=5:

#!/usr/bin/env python #-*-encoding:utf-8-*-# author:kentzhan #  Import HEAPQ import random  heap = [] heapq.he Apify (heap) for I in range:  item = Random.randint (Ten)  print "Comeing", item,  if Len (heap) >= 5:
  top_item = heap[0] # smallest in heap   if Top_item < item: # min heap    top_item = Heapq.heappop (heap)    PR int "Pop", Top_item,    heapq.heappush (heap, item)    print "Push", item,  else:   heapq.heappush (Heap, Item)   print "Push", item,  pass  print heap pass print heap  print "sort" heap.sort ()  print heap

Results:

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.