Heapq heap related methods in Python

background

In LeetCode, many topics can be implemented using priority queues. The data structure in Python is heapq, and the heap in Python is a small top heap. Heap[0] is always the smallest element. Today, I will summarize the common methods

insert image description here

common method

add element

>>> import heapq
>>> my_list = []
>>> heapq.heappush(my_list,2)
>>> my_list
[2]

remove and return the smallest element

>>> my_list
[1, 1, 3, 5, 2, 5, 8, 9, 6]
>>> heapq.heappop(my_list)
1
>>> my_list
[1, 2, 3, 5, 6, 5, 8, 9]

Query the largest n elements in the heap

>>> my_list
[3, 5, 5, 9, 6, 6, 8, 99]
>>> heapq.nlargest(3,my_list)
[99, 9, 8]

Query the minimum n elements in the heap

>>> my_list
[3, 5, 5, 9, 6, 6, 8, 99]
>>> heapq.nsmallest(3,my_list)
[3, 5, 5]

list to heap

>>> my_list = [1,2,3,5,1,5,8,9,6]
>>> heapq.heapify(my_list)
>>> my_list
[1, 1, 3, 5, 2, 5, 8, 9, 6]

Guess you like

Origin blog.csdn.net/m0_46521785/article/details/123621223