Is there a heap in python?

(*-*)浩
Release: 2019-08-01 10:10:39
Original
2627 people have browsed it

Heap (English: heap) is the collective name for a special type of data structure in computer science;

Is there a heap in python?

The definition of heap: a sequence of n elements { k1,k2,ki,…,kn} If and only if the following relationship is satisfied, it is called a heap. (Recommended learning: Python video tutorial)

"ki<=k2i,ki<=k2i+1;或ki>=k2i,ki>=k2i+1.(i=1,2,…,[n/2])"
Copy after login

This is the standard heap definition, but there is no independent heap type in python, it is just a module that contains some heap operation functions (heapq = the first letter of heap queue), in fact, the heap is a special list in python;

Briefly introduce the methods in heapq

import heapq
1.heapq.heappush(heap,item)  #heap为定义堆,item 增加的元素;
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)     #删除最小元素值,添加新的元素值
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)     #首判断添加元素值与堆的第一个元素值对比,如果大于则删除最小元素,然后添加新的元素值,否则不更改堆
eg.
   条件: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]
   条件: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表示查询元素个数
eg.
  heap=[2, 3, 5, 6, 4, 8, 7, 9]
  heapq.nlargest (1, heap)--->[9]
8.heapq.nsmallest(n, heap)     #查询堆中的最小元素,n表示查询元素个数
eg.
 heap=[2, 3, 5, 6, 4, 8, 7, 9]
 heapq.nlargest (1, heap)--->[2]
Copy after login

More Python related technologies Article, please visit the Python Tutorial column to learn!

The above is the detailed content of Is there a heap in python?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!