Python中的堆队列(或heapq)
堆数据结构主要用来表示一个优先级队列。在Python中,可以使用“ heapq ”模块。 Python中这种数据结构的属性是每次弹出最小的堆元素(min heap) 。每当元素被推送或弹出时,堆结构都会被维护。 heap[0] 元素每次也返回最小的元素。
让我们看看堆上的各种操作:
- heapify(可迭代) :- 此函数用于将可迭代对象转换为堆数据结构。即按堆顺序。
- heappush(heap, ele) :- 此函数用于将其参数中提到的元素插入堆中。调整顺序,从而保持堆结构。
- heappop(堆) :- 此函数用于从堆中删除并返回最小元素。调整顺序,从而保持堆结构。
# Python code to demonstrate working of
# heapify(), heappush() and heappop()
# importing "heapq" to implement heap queue
import heapq
# initializing list
li = [5, 7, 9, 1, 3]
# using heapify to convert list into heap
heapq.heapify(li)
# printing created heap
print ("The created heap is : ",end="")
print (list(li))
# using heappush() to push elements into heap
# pushes 4
heapq.heappush(li,4)
# printing modified heap
print ("The modified heap after push is : ",end="")
print (list(li))
# using heappop() to pop smallest element
print ("The popped and smallest element is : ",end="")
print (heapq.heappop(li))
输出 :
The created heap is : [1, 3, 9, 7, 5]
The modified heap after push is : [1, 3, 4, 7, 5, 9]
The popped and smallest element is : 1
- heappushpop(堆,电子) :- 此函数将 push 和 pop 操作的功能结合在一个语句中,提高了效率。此操作后,堆顺序保持不变。
- heapreplace(heap, ele) :- 这个函数也在一个语句中插入和弹出元素,但它与上面的函数不同。在这种情况下,先弹出元素,然后再推送元素。即可以返回大于推送值的值。
heapreplace()
返回最初在堆中的最小值,而不考虑推送的元素,而不是heappushpop()
。
# Python code to demonstrate working of
# heappushpop() and heapreplce()
# importing "heapq" to implement heap queue
import heapq
# initializing list 1
li1 = [5, 7, 9, 4, 3]
# initializing list 2
li2 = [5, 7, 9, 4, 3]
# using heapify() to convert list into heap
heapq.heapify(li1)
heapq.heapify(li2)
# using heappushpop() to push and pop items simultaneously
# pops 2
print ("The popped item using heappushpop() is : ",end="")
print (heapq.heappushpop(li1, 2))
# using heapreplace() to push and pop items simultaneously
# pops 3
print ("The popped item using heapreplace() is : ",end="")
print (heapq.heapreplace(li2, 2))
输出 :
The popped item using heappushpop() is : 2
The popped item using heapreplace() is : 3
- nlargest(k, 可迭代, key = fun) :- 此函数用于从指定的可迭代对象中返回 k 个最大的元素,并满足键(如果提到)。
- nsmallest(k, iterable, key = fun) :- 此函数用于从指定的可迭代对象中返回 k 个最小元素,并满足键(如果提到)。
# Python code to demonstrate working of
# nlargest() and nsmallest()
# importing "heapq" to implement heap queue
import heapq
# initializing list
li1 = [6, 7, 9, 4, 3, 5, 8, 10, 1]
# using heapify() to convert list into heap
heapq.heapify(li1)
# using nlargest to print 3 largest numbers
# prints 10, 9 and 8
print("The 3 largest numbers in list are : ",end="")
print(heapq.nlargest(3, li1))
# using nsmallest to print 3 smallest numbers
# prints 1, 3 and 4
print("The 3 smallest numbers in list are : ",end="")
print(heapq.nsmallest(3, li1))
输出 :
The 3 largest numbers in list are : [10, 9, 8]
The 3 smallest numbers in list are : [1, 3, 4]