SoFunction
Updated on 2024-12-16

About Python's Advanced Data Structures and Algorithms

I. Introduction

In this article, we will learn about advanced data structures in Python such as heaps, stacks, queues, chain tables, etc. and implement common algorithms such as sorting, finding, etc. using Python. We will start this article with the following aspects:

Stack

Queue

Linked List

Heap

Sorting Algorithms

Searching Algorithms

Second, the stack (Stack)

A stack is a last-in-first-out (LIFO) data structure that only allows insertion and deletion operations at the top of the stack. In Python, we can implement a stack using a list.

class Stack:
    def __init__(self):
         = []
 
    def push(self, item):
        (item)
 
    def pop(self):
        if not self.is_empty():
            return ()
 
    def peek(self):
        if not self.is_empty():
            return [-1]
 
    def is_empty(self):
        return len() == 0
 
    def size(self):
        return len()

III. Queues (Queue)

A queue is a first-in-first-out (FIFO) data structure that only allows insertion operations at the end of the queue and deletion operations at the head of the queue. In Python, we can use thecollectionsin the moduledequeclass implements the queue.

from collections import deque
 
class Queue:
    def __init__(self):
         = deque()
 
    def enqueue(self, item):
        (item)
 
    def dequeue(self):
        if not self.is_empty():
            return ()
 
    def is_empty(self):
        return len() == 0
 
    def size(self):
        return len()
             = 
    else:
        raise ValueError("Data not found in the list")

IV. Heap

A heap is a special kind of complete binary tree in which each node is greater than or equal to (maximal heap) or less than or equal to (minimal heap) its children. In Python, we can use theheapqThe library realizes the heap.

import heapq
 
class MaxHeap:
    def __init__(self):
         = []
 
    def push(self, item):
        (, -item)
 
    def pop(self):
        return -()
 
    def peek(self):
        return -[0]
 
    def is_empty(self):
        return len() == 0
 
    def size(self):
        return len()
 

V. Sorting Algorithms

1. Bubble Sort

Bubble sort is a simple sorting algorithm that repeatedly traverses a list by comparing neighboring elements and swapping incorrect orders.

 
def bubble_sort(arr):
    n = len(arr)
    for i in range(n):
        for j in range(0, n - i - 1):
            if arr[j] > arr[j + 1]:
                arr[j], arr[j + 1] = arr[j + 1], arr[j]

2. Selection Sort

Selection sort is a simple sorting algorithm that traverses the list one at a time to find the smallest (or largest) element and place it in the correct position.

def selection_sort(arr):
    n = len(arr)
    for i in range(n):
        min_index = i
        for j in range(i + 1, n):
            if arr[j] < arr[min_index]:
                min_index = j
        arr[i], arr[min_index] = arr[min_index], arr[i]

3. Insertion Sort

Insertion sort is a simple sorting algorithm that inserts unsorted elements one by one into a sorted sequence.

def insertion_sort(arr):
    n = len(arr)
    for i in range(1, n):
        key = arr[i]
        j = i - 1
        while j >= 0 and arr[j] > key:
            arr[j + 1] = arr[j]
            j -= 1
        arr[j + 1] = key

VI. Finding Algorithms (Searching Algorithms)

1. Sequential Search

Sequential lookup is a simple lookup algorithm that finds a target value by traversing a list and comparing elements one by one.

def sequential_search(arr, target):
    for i in range(len(arr)):
        if arr[i] == target:
            return i
    return -1

2. Binary Search

Dichotomous lookup is an efficient lookup algorithm that requires the list to be sorted. Each lookup reduces the range by half until the target value is found.

def binary_search(arr, target):
    low, high = 0, len(arr) - 1
    while low <= high:
        mid = (low + high) // 2
        if arr[mid] == target:
            return mid
    elif arr[mid] < target:
        low = mid + 1
    else:
        high = mid - 1
return -1

wrap-up

In this article, we learn advanced data structures in Python, such as stack, queue, chain table, heap, and implement common sorting and finding algorithms. Mastering these data structures and algorithms will help us solve various problems in real programming and improve our programming skills and proficiency.

In the subsequent articles, we will continue to explore more real-world Python cases, such as web programming, data analysis, crawling, machine learning, etc. We hope these articles can help you in your study and practice.

This article on Python's advanced data structures and algorithms is introduced to this, more related Python data structures and algorithms content, please search for my previous articles or continue to browse the following related articles I hope you will support me more in the future!