<jupyter_start><jupyter_text>Heap is a special **tree structure** in which **each parent node is less than or equal to its child node**. Then it is called a **Min Heap**. If each parent node is greater than or equal to its child node then it is called a **max heap**. It is very useful in implementing **priority queues** where the queue item with higher weightage is given more priority in processing. *** Create a HeapA heap is created by using python’s inbuilt library named `heapq`. This library has the relevant functions to carry out various operations on heap data structure. Below is a list of these functions.- `heapify` - This function converts a regular list to a heap. In the resulting heap the smallest element gets pushed to the index position 0. But rest of the data elements are not necessarily sorted.将列表转化为heap，并且第一个元素是最小的，后面heap中元素则是乱序的- `heappush` – This function adds an element to the heap without altering the current heap.将元素添加到heap尾部- `heappop` - This function returns the smallest data element from the heap.弹出heap中的第一个也就是最小元素- `heapreplace` – This function replaces the smallest data element with a new value supplied in the function.替换最小元素为新元素<jupyter_code># convert list to heap

import heapq

H = [21,1,45,78,3,5]
# Use heapify to rearrange the elements
heapq.heapify(H)
print(H)
# push element to the end of heap

import heapq

H = [21,1,45,78,3,5]
# Covert to a heap
heapq.heapify(H)
print(H)
# Add element
heapq.heappush(H,8)
print(H)
# pop

import heapq

H = [21,1,45,78,3,5]
# Create the heap

heapq.heapify(H)
print(H)

# Remove element from the heap
heapq.heappop(H)

print(H)
# replace
# The heapreplace function always removes the smallest element 
# of the heap and inserts the new incoming element 
# at some place not fixed by any order.

import heapq

H = [21,1,45,78,3,5]
# Create the heap

heapq.heapify(H)
print(H)

# Replace an element
heapq.heapreplace(H,6)
print(H)<jupyter_output>[1, 3, 5, 78, 21, 45]
[3, 6, 5, 78, 21, 45]
{'fraction_non_alphanumeric': 0.08261530663963507, 'fraction_numerical': 0.02889001520527116, 'mean_word_length': 4.688760806916426, 'pattern_counts': {'":': 0, '<': 4, '<?xml version=': 0, '>': 4, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '233946', 'license': 'MIT', 'n_tokens_mistral': 683, 'n_tokens_neox': 654, 'n_words': 285, 'path': 'fundamentals/.ipynb_checkpoints/Heap-checkpoint.ipynb', 'repo_name': 'lance-lh/Data-Structures-and-Algorithms', 'size': '1973'}