Python Learning Notes (heap usage in python)

Source: Internet
Author: User

Heap: One of the priority queues that use the priority queue to increase the object in any order, and to find (or possibly remove) the smallest element at any time (possibly at the same time as the object is incremented), which is more efficient than the method used for min in the list.

Python does not have a separate heap type, only a module that includes some heap operation functions, called HEAPQ.

Import HEAPQ

1.heapq.heappush (Heap,item) #heap为定义堆, item added element;

eg.

Heap=[]
Heapq.heappush (heap, 2)

2.heapq.heapify (list) #将列表转换为堆

eg.

list=[5,8,0,3,6,7,9,1,4,2]

Heapq.heapify (list)

3.heapq.heappop (heap) #删除最小的值

eg.

Heap=[2, 4, 3, 5, 7, 8, 9, 6]

Heapq.heappop (heap)---->heap=[3, 4, 5, 7, 9, 6, 8]

4.heapq.heapreplace (Heap,item) #删除最小元素值, add a new element value

eg.

Heap=[2, 4, 3, 5, 7, 8, 9, 6]

Heapq.heapreplace (heap,11)------>heap=[2, 3, 4, 6, 8, 5, 7, 9, 11]

5.heapq.heappushpop (Heap,item) #首判断添加元素值与堆的第一个元素值对比, if it is greater then remove the smallest element, and then add a new element value, otherwise do not change the heap

eg.

Condition: Item >heap[0]

Heap=[2, 4, 3, 5, 7, 8, 9, 6]

Heapq.heappushpop (heap, 9)---->heap=[3, 4, 5, 6, 8, 9, 9,7]

Condition: Item

Heap=[2, 4, 3, 5, 7, 8, 9, 6]

Heapq.heappushpop (heap, 9)---->heap=[2, 4, 3, 5, 7, 8, 9,6]

6.heapq.merge (...) #将多个堆合并

7.heapq.nlargest (n,heap) #查询堆中的最大元素, n indicates the number of query elements

eg.

Heap=[2, 3, 5, 6, 4, 8, 7, 9]

Heapq.nlargest (1,HEAP)--->[9]
8.heapq.nsmallest (n,heap) #查询堆中的最小元素, n indicates the number of query elements

eg.

Heap=[2, 3, 5, 6, 4, 8, 7, 9]

Heapq.nlargest (1,HEAP)--->[2]

Python Learning Notes (heap usage in python)

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.