Python algorithm-divide and conquer idea and quick sort (with case)

This time we will learn an important idea in the algorithm-divide and conquer

Divide and conquer

A well-known recursive problem solution. When we encounter a problem, we can use the known algorithm to solve it. We can try to use the solutions to various problems we have mastered to find a solution. Divide and conquer is one of learning. A general problem solving method
Case 1: Suppose you are a farmer and have a small piece of land. You need to divide this piece of land into squares evenly, and the divided squares should be as large as possible

def tudi(a, b):
    if a % b == 0:
        return f"每块地最大的大小为{b**2}"
    else:
        a, b = b, a % b
        return tudi(a, b)

print(tudi(1680, 640))

Case 2: Given an array of numbers, you need to add these numbers and return the result

def num_sum(my_list):
    if len(my_list) == 0:
        return 0
    else:
        num = my_list[0]
        my_list.remove(num)
        return num + num_sum(my_list)

print(num_sum([1, 2, 3, 4, 5]))

Find the largest number in the list

def max(my_list):
    if len(my_list) == 1:
        return my_list
    else:
        if my_list[0] < my_list[1]:
            my_list.remove(my_list[0])
        else:
            my_list.remove(my_list[1])
        return max(my_list)

print(max([1, 2, 3, 4, 10, 5]))

Quick sort

The next thing I want to introduce is another highlight of today-quick sort.

Quick sort is a commonly used sorting algorithm, and quick sort also uses the idea of ​​divide and conquer

First, we first find the baseline condition: there are only 1 or 0 elements in the list,
and then the recursive condition: first define a reference value ((num), by comparing with the reference value, the list is divided into 3 parts, that is, proceed Partitions: 1. A sub-array composed of less than the benchmark value 2. The benchmark value 3. A sub-array composed of greater than the benchmark value

def quicksort(my_list):
    if len(my_list) < 2:  # 基线条件   列表中只有1个或0个元素
        return my_list
    else:  # 递归条件
        num = my_list[0]  # 将列表的第一个数定义为基准值
        list_a = [i for i in my_list[1:] if i <= num]  # 比基准值小的放在一个列表
        list_b = [i for i in my_list[1:] if i > num]  # 比基准值大的放在一个列表
        return quicksort(list_a) + [num] + quicksort(list_b)

print(quicksort([1, 22, 3, 4, 5, 6, 7, 8, 9]))

Guess you like

Origin blog.csdn.net/Layfolk_XK/article/details/108294086