Home > Article > Backend Development > In-depth understanding of Python's heapq built-in module introduction
heapq is a built-in module of python. The source code is located in Lib/heapq.py. This module provides a heap-based prioritization algorithm.
The logical structure of the heap is a complete binary tree, and the value of the parent node in the binary tree is less than or equal to the value of all the child nodes of the node. This implementation can use heap[k] <= heap[2k+1] and heap[k] <= heap[2k+2] (where k is the index, counting from 0) Formal expression, for a heap, the smallest element is the root element heap[0].
You can initialize the heap through list, or convert the known list into a heap through heapify in api Object.
Functions provided by heapqMethods
heapq.heappush(heap, item)
heapq.heappop(heap): Return the root node, which is the smallest element in the heap
heapq.heappushpop(heap, item): Add the item element to the heap and return the smallest element in the heap
heapq.heapify(x)
heapq.nlargest(n, iterable, key=None): Returns the n largest values in the enumerable object, and returns a result set list, the key is the result set Operation
heapq.nsmallest(n, iterable, key=None): Same as above but opposite
demo
1. Sort the list through heapq api
def heapsort(iterable): h = [] for i in iterable: heapq.heappush(h, i) return [heapq.heappop(h) for i in range(len(h))] s = [3, 5, 1, 2, 4, 6, 0, 1] print(heapsort(s))
The output is as follows
[0, 1, 1, 2, 3, 4, 5, 6]
2. Find the smallest price in the object list through key An item
portfolio = [ {'name': 'IBM', 'shares': 100, 'price': 91.1}, {'name': 'AAPL', 'shares': 50, 'price': 543.22}, {'name': 'FB', 'shares': 200, 'price': 21.09}, {'name': 'HPQ', 'shares': 35, 'price': 31.75}, {'name': 'YHOO', 'shares': 45, 'price': 16.35}, {'name': 'ACME', 'shares': 75, 'price': 115.65} ] cheap = heapq.nsmallest(1, portfolio, key=lambda s: s['price']) print(cheap)
is output as follows
[{'shares': 45, 'price': 16.35, 'name': 'YHOO'}]As mentioned above, heapq is the implementation of the minimum heap, so let's analyze how to convert the list into a minimum heap through the API in Python based on the source code of heapq (the keywords of the parent node are smaller than the left and right child nodes) ) can be divided into the following steps: 1. Starting from the last element with a child node, treat this parent node element and its child nodes as a unit2. In the unit, swap the smaller element of the two child nodes with the parent node (there is no need to judge the size relationship between the parent node and the smallest child node). Through this step, you can change the unit to the smallest one. Heap unit 3. Through
while loop you can push smaller elements upward
def heapilize_list(x): n = len(x) # 获取存在子节点的节点 index 列表,并对每个节点单元进行最小堆处理 for i in reversed(range(n // 2)): raiseup_node(x, i) def put_down_node(heap, startpos, pos): current_item = heap[pos] # 判断单元中最小子节点与父节点的大小 while pos > startpos: parent_pos = (pos - 1) >> 1 parent_item = heap[parent_pos] if current_item < parent_item: heap[pos] = parent_item pos = parent_pos continue break heap[pos] = current_item def raiseup_node(heap, pos): heap_len = len(heap) start_pos = pos current_item = heap[pos] left_child_pos = pos * 2 + 1 while left_child_pos < heap_len: right_child_pos = left_child_pos + 1 # 将这个单元中的最小子节点元素与父节点元素进行位置调换 if right_child_pos < heap_len and not heap[left_child_pos] < heap[right_child_pos]: left_child_pos = right_child_pos heap[pos] = heap[left_child_pos] pos = left_child_pos left_child_pos = pos * 2 + 1 heap[pos] = current_item put_down_node(heap, start_pos, pos) p = [4, 6, 2, 10, 1] heapilize_list(p) print(p)The output is as follows
[1, 6, 2, 10, 4]
The above is the detailed content of In-depth understanding of Python's heapq built-in module introduction. For more information, please follow other related articles on the PHP Chinese website!