This article illustrates how Python uses the divide-and-conquer method to achieve the maximum value. Share to everyone for your reference. The specific analysis is as follows:
Given a sequential table, a divide-and-conquer algorithm to find out its maximum value and minimum value is compiled.
Since the structure of the sequential table is not given, as a demonstration of the divide-and-conquer method here, a simple order table is taken. The size of an array is defined by the user and randomly generated by the data. We know that if the array size is 1, we can give the result directly, if the size is 2 then the result is a comparison, so we find the child problem that solves the problem namely: Array size <= 2. So we can divide and conquer operations, as long as the problem array length than 2 continue to divide, otherwise solve the problem of the solution and update the global solution is the following code.
Understand the topic to say, the key is to decompose the order table into a list of K element 2, and then find the maximum value of the list, and then the list of problems to merge, and then recursive solution.
On the Code bar:
|1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23-24||#-*-coding:utf-8-*-#分治法求解最大值问题 import random #求解两个元素的列表的最大值方法 def max_value (max_list): Return Max (max_list) #定义求解的递归方法 def solve (init_list): If Len (init_list) <= 2: #若列表元素个数小于等于2, output print max_value (init_list) Else:init_list=[init_li ST[I:I+2] for I in range (0,len (init_list), 2)] #将列表分解为列表长度除以2个列表 max_init_list =  #用于合并求最大值的列表 for _list in init_list: #将 Solution list for each child problem merge Max_init_list.append (Max_value (_list)) solve (max_init_list) if __name__ = "__main__": Test_list = [ 12,2,23,45,67,3,2,4,45,63,24,23] #测试列表 Solve (test_list)|
I hope this article will help you with your Python programming.