[Python] This article takes you to learn the heap and stack in the data structure

 

Author's homepage: boy who loves to laugh. Blog_CSDN blog - deep learning, activities, python field blogger loves to laugh boy. A boy who is good at deep learning, activities, python, etc., and loves to laugh. Focus on algorithms, python, computer vision, image processing, deep learning, pytorch, neural network, opencv fields. https://blog.csdn.net/Code_and516?type=blog Personal profile: Dagong.

Continue to share: machine learning, deep learning, python-related content, daily BUG solutions, and Windows&Linux practical tips.

If you find an error in the article, please point it out, and I will correct it in time. If you have other needs, you can private message me or send me an email: [email protected] 

        Heap is a special data structure with excellent performance and flexible application scenarios. In Python, the heap can be implemented with the built-in heapq module. A stack is a very important data structure that is often used to solve various computer science problems.

This article will explain in detail the heap and stack in the Python data structure


Table of contents

pile

1.1 Introduction to the heap

1.1.1 Definition of heap

1.1.2 Representation method of heap

1.1.3 Heap operations

1.2 History of Heap

1.2.1 Binary heap

1.2.2 Fibonacci pile

1.2.3 Priority queue

1.3 How to use the heap

1.3.1 Create heap

1.3.2 Inserting elements

1.3.3 Popup elements

1.3.4 Replacement elements

1.3.5 Merging the heap

1.3.6 Heap sort

1.4 Summary of the heap

Two, the stack

2.1 Introduction to the stack

2.1.1 Definition of stack

2.1.2 Characteristics of the stack

2.1.3 Application scenarios of the stack

2.2 The development history of the stack

2.2.1 Early Stack (Early Stack)

2.2.2 Array-Based Stack

2.2.3 Linked List-Based Stack

2.2.4 Dynamic Array-Based Stack

2.3 How to use the stack

2.3.1 Initialize the stack

2.3.2 Push (push)

2.3.3 Popping the stack (popping the stack)

2.3.4 Get the top element of the stack

2.3.5 Determine whether the stack is empty 

2.3.6 Display the elements of the stack 

2.3.7 The comprehensive sample code is as follows:

2.4 Summary of the stack

2.4.1 The characteristics of the stack:

2.4.2 Basic operation:

2.4.3 Application of the stack:

2.4.4 Implementation of the stack:


pile

1.1 Introduction to the heap

1.1.1 Definition of heap

        A heap is a special tree-like data structure that satisfies the following two main properties:

  • A heap is a complete binary tree: all levels in the heap except the last level are completely filled, and the nodes in the last level are arranged to the left.
  • The value of any node of the heap is not greater than (or not less than) the value of its child nodes: this property is called the heap property.

        According to the different properties of the heap, the heap can be divided into a maximum heap and a minimum heap.

1.1.2 Representation method of heap

        In Python, a list can be used to represent a heap. Specifically, the first element (index 0) of the heap is the root node, and other elements are arranged in order from top to bottom and left to right.

1.1.3 Heap operations

        The heap mainly supports the following operations:

  • Insert: insert a new element into the heap, and maintain the structure and properties of the heap.
  • Remove minimum (or maximum) value: remove the root node in the heap, and keep the structure and properties of the heap.
  • Build a heap: Build a new heap, converting an unordered list into a heap.

1.2 History of Heap

        As a classic data structure, the heap was born in the 1960s and was first proposed by Edgar F. Codd in the database field. Later, the heap was applied to the research of algorithms and data structures, and a variety of different usage forms were derived.

1.2.1 Binary heap

        Binary heap is the most basic form of heap and the most common implementation of heap. It satisfies the definition of a heap while using the structure of a complete binary tree. In a binary heap, the value of each node is not less than (or not greater than) the value of its child nodes.

1.2.2 Fibonacci pile

        Fibonacci heaps are proposed to solve the problem of inefficiency in certain operations of binary heaps. Fibonacci heaps will support a set of heap structures consisting of binomial heaps, pairing heaps, and Fibonacci heaps. Compared with binary heap, Fibonacci heap has better amortized time complexity, but also brings greater constant time.

1.2.3 Priority queue

        A priority queue is a special data structure, and a heap is one of the common ways to implement a priority queue. Each element in the priority queue has a priority, and elements with higher priority are listed first. The heap can well support the insertion and deletion operations of the priority queue, keeping the elements in the queue in order according to the priority.

1.3 How to use the heap

        First, we need to import the Python heapqmodule, which is the module used to implement the heap in the Python standard library. Import using the following statement:

import heapq

        Next, I will introduce the basic operations of the heap one by one.

1.3.1 Create heap

        In Python, we can use heapqmodules to create heaps. A list can heapq.heapify()be converted to a heap by a function. Here is an example:

import heapq

data = [5, 2, 8, 0, 3, 9, 1]
heapq.heapify(data)
print(data)  # 输出: [0, 2, 1, 5, 3, 9, 8]

        As you can see, through heapify()the function, the list datais converted into a heap. 

1.3.2 Inserting elements

        To insert an element in the heap, heapq.heappush()a function can be used. Here is an example:

import heapq

data = [5, 2, 8, 0, 3, 9, 1]
heapq.heapify(data)
heapq.heappush(data, 6)
print(data)  # 输出: [0, 2, 1, 5, 3, 9, 8, 6]

         It can be seen that through heappush()the function, element 6 is inserted into the heap, and the characteristics of the heap are preserved.

1.3.3 Popup elements

        To pop the smallest (or largest) element from the heap, you can use heapq.heappop()a function. Here is an example:

import heapq

data = [0, 2, 1, 5, 3, 9, 8]
heapq.heapify(data)
smallest = heapq.heappop(data)
print(smallest)  # 输出: 0
print(data)  # 输出: [1, 2, 8, 5, 3, 9]

        It can be seen that through heappop()the function, the minimum value 0 in the heap is popped, and the characteristics of the heap are maintained. 

1.3.4 Replacement elements

        Replacing elements in the heap is similar to popping elements, and heapq.heapreplace()functions can be used. Here is an example:

import heapq

data = [0, 2, 1, 5, 3, 9, 8]
heapq.heapify(data)
smallest = heapq.heapreplace(data, 7)
print(smallest)  # 输出: 0
print(data)  # 输出: [1, 2, 7, 5, 3, 9, 8]

        It can be seen that through heapreplace()the function, the minimum value 0 in the heap is popped and replaced by element 7. The replacement operation does not need to pop the minimum value first and then insert the new element, so it is more efficient. 

1.3.5 Merging the heap

        Functions can be used heapq.merge()to merge multiple heaps and return a new heap. Here is an example:

import heapq

heap1 = [1, 3, 5]
heap2 = [2, 4, 6]
merged = heapq.merge(heap1, heap2)
print(list(merged))  # 输出: [1, 2, 3, 4, 5, 6]

        It can be seen that through merge()the function, the heap sum heap1is heap2merged into a new heap. 

1.3.6 Heap sort

        Heap sorting is a method of sorting a list using the properties of the heap. Heapsort can be implemented using functions and functions heapqin the module . Here is an example:heappushpop()heapq.nsmallest()

import heapq

data = [5, 2, 8, 0, 3, 9, 1]
sorted_data = [heapq.heappop(data) for _ in range(len(data))]
print(sorted_data)  # 输出: [0, 1, 2, 3, 5, 8, 9]

        It can be seen that the sorting of the list is achieved by popping the smallest element in the heap multiple times. 

1.4 Summary of the heap

        The heap is a very powerful data structure in Python, which has the following advantages:

  • Efficient insertion and deletion operations: The operation time complexity of inserting and deleting the minimum (or maximum) value of the heap is O(log n), which can maintain high performance even in large-scale data processing.
  • Get the most value quickly: the root node of the heap is the minimum (or maximum) value, which can be obtained in O(1) time.
  • Flexible application scenarios: Heaps are widely used in priority queues, sorting algorithms (such as heap sorting), and graph algorithms (such as Dijkstra's shortest path algorithm), etc.

        However, heaps also have some limitations:

  • Not suitable for search and modification operations: Since the heap is not arranged in order, the specified element cannot be quickly found for modification.
  • Cannot keep order: the heap does not require all elements to be in order, it only guarantees the order of the most value.
  • Large footprint: The implementation of the heap requires additional storage space, some of which may never be accessed.

        In general, the heap is a powerful and flexible data structure, especially suitable for scenarios with frequent operations on the most value. In Python, the built-in heapq module provides a heap implementation. Developers can use this module to quickly apply heap data structures and improve program efficiency and performance.

Two, the stack

2.1 Introduction to the stack

2.1.1 Definition of stack

        A stack is a linear data structure characterized by Last-In-First-Out (LIFO). The stack has two main operations, Push and Pop. Pushing puts data on top of the stack, while popping removes data from the top of the stack. In addition, the stack also has the function of returning the top element of the stack (Top).

2.1.2 Characteristics of the stack

  1. In addition to following the last-in-first-out principle, the stack has the following characteristics:

  • The capacity of the stack is fixed. When the stack reaches its maximum capacity, another push operation will cause the stack to overflow.
  • The stack can be empty or reach its maximum capacity.
  • Elements in the stack are not randomly accessible. The top element of the stack can only be obtained by popping the stack.

2.1.3 Application scenarios of the stack

        The characteristics of the stack make it widely used in many fields. Common application scenarios include:

  • Reverse order output: The stack can be used to output the input string in reverse order.
  • Expression Computation: Stacks can be used to process mathematical expressions and resolve priority issues.
  • Function call: The stack is used to store local variables and return addresses during function calls.
  • Browser back: The browser's "back" function is implemented through a stack.

2.2 The development history of the stack

2.2.1 Early Stack (Early Stack)

        Early computers had limited memory and therefore limited data structure design. The implementation of the early computer stack is to use the stack pointer (Stack Pointer) as a register. The computer realizes the management of function calls and return addresses by storing instructions and data in the stack on the memory.

2.2.2 Array-Based Stack

        With the improvement of computer memory, the stack can be implemented using an array, by defining a fixed-size array to store the elements in the stack. The array stack has a high access speed, but its capacity is fixed.

2.2.3 Linked List-Based Stack

        In order to overcome the problem of fixed array stack capacity, Linked List-Based Stack (Linked List-Based Stack) provides a dynamic stack implementation. The linked list stack uses the linked list structure to store the elements in the stack, so that the capacity of the stack can be dynamically increased or decreased according to demand. Linked list stacks usually require more memory space for storing pointers.

2.2.4 Dynamic Array-Based Stack

        A dynamic array stack is a combination of an array stack and a linked list stack. It uses arrays to store elements in the stack, but has the ability to grow and shrink dynamically. When the size of the stack exceeds the capacity of the array, the dynamic array stack will automatically reallocate a larger memory space. Compared with the linked list stack, the access speed of the dynamic array stack is faster, but additional memory allocation and data copy operations are required for expansion.

2.3 How to use the stack

        Stack is a common data structure, which is characterized by "Last-In-First-Out" (Last-In-First-Out, LIFO). In Python, we can use a list (List) to implement a stack.

2.3.1 Initialize the stack

        Initialize an empty stack, which can be represented by an empty list. The sample code is as follows:

stack = []

2.3.2 Push (push)

        Adding an element to the top of the stack is called pushing or pushing. append() Elements can be added to the end of the stack using list  methods. The sample code is as follows:

stack.append(1)
stack.append(2)
stack.append(3)

        The elements of the stack now become [1, 2, 3]

2.3.3 Popping the stack (popping the stack)

        Removing elements from the top of the stack is called popping or popping. pop() The top element of the stack can be removed and returned using the list  method. The sample code is as follows:

element = stack.pop()
print(element)  # 输出:3

        The elements of the stack now become [1, 2]

2.3.4 Get the top element of the stack

        Get the top element of the stack without removing it. You can directly use the index of the list  -1 to get the top element of the stack. The sample code is as follows:

top_element = stack[-1]
print(top_element)  # 输出:2

2.3.5 Determine whether the stack is empty 

        You can determine whether the stack is empty by checking whether the length of the stack is zero. You can use the list  len() method to get the length of the stack. The sample code is as follows:

python
is_empty = len(stack) == 0
print(is_empty)  # 输出:False

2.3.6 Display the elements of the stack 

        The elements of the stack can be displayed using a loop over the list. The sample code is as follows:

for element in stack:
    print(element)
# 输出:
# 1
# 2

2.3.7 The comprehensive sample code is as follows:

stack = []
stack.append(1)
stack.append(2)
stack.append(3)

element = stack.pop()
print(element)  # 输出:3

top_element = stack[-1]
print(top_element)  # 输出:2

is_empty = len(stack) == 0
print(is_empty)  # 输出:False

for element in stack:
    print(element)
# 输出:
# 1
# 2

        Stacks are widely used in practical applications, such as recursive function calls, expression evaluation, depth-first search, etc. Mastering the use of the stack is very important for Python programming.

2.4 Summary of the stack

2.4.1 The characteristics of the stack:

        The stack is a restricted linear data structure, and the order of storing elements follows the "last in, first out" principle. Due to the particularity of stack operations, the stack has some unique properties: insertion and deletion with constant time complexity, but only the top element of the stack can be accessed.

2.4.2 Basic operation:

  • Push: Add an element to the top of the stack.
  • Pop (pop): Delete the top element of the stack and return its value.
  • Get the top element of the stack (top): returns the value of the top element of the stack.
  • Whether the stack is empty (isEmpty): Determine whether the stack is empty.
  • Stack size (size): returns the number of elements in the stack.

2.4.3 Application of the stack:

  • Function call: The calling sequence of functions is recorded using the stack. Whenever a function is called, its call information is pushed into the stack, and it is popped up after the function is executed.
  • Bracket matching: The stack can be used to check whether the parentheses in the expression match. When encountering a left parenthesis, it is pushed onto the stack, and when a right parenthesis is encountered, it is matched with the top element of the stack.
  • Browser forward and backward: the forward and backward functions of the browser can be realized through two stacks, one stack is used to store the user's browsing records, and the other stack is used to store the user's back records.

2.4.4 Implementation of the stack:

        In Python, you can use a list (list) to implement the function of the stack. The stack operation is realized by the append() method of the list, and the stack operation is realized by the pop() method. In addition, you can also use the deque in the collections module to implement the stack. The deque is a double-ended queue that can achieve efficient stacking and popping operations.

        To sum up, the stack, as a constrained linear data structure, has a wide range of applications in computer science. Its development begins with the hardware system, and has been further expanded with the development of the software system. Stack is not only a concept in data structure, but also a tool and way of thinking that we commonly use in programming. Mastering the basic concepts and operations of the stack is important for understanding how algorithms and programming languages ​​work.

 

Guess you like

Origin blog.csdn.net/Code_and516/article/details/131476085