Python method for solving maximum value using divide-and-conquer method

Source: Internet
Author: User
In this paper, we describe the method by which Python uses divide-and-conquer method to solve maximum value. Share to everyone for your reference. The specific analysis is as follows:

Topic:

Given a sequential table, a divide-and-conquer algorithm is written to find out its maximum and minimum values.

Analysis:

Since the structure of the sequential table is not given, as a demonstration of the divide-and-conquer method here the Simple order table takes a shape array array size defined by the user, the data is randomly generated. We know that if the array size is 1, you can give the result directly, and if the size is 2 a comparison can be obtained, so we find a sub-problem to solve the problem that is: array size <= 2. In this case, we can divide and conquer, as long as the problem of the array length is greater than 2 to continue to divide, otherwise the solution of the sub-problem and update the global solution below is the code.

Read the topic to say, the key is to decompose the order table into a list of K elements 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:

#-*-coding:utf-8-*-#分治法求解最大值问题import random# The maximum method for solving a list of two elements Def Max_value (max_list):  return Max (max_list) # Define a recursive method for solving def solve (init_list):  If Len (init_list) <= 2:  #若列表元素个数小于等于2, the output    print max_value (init_list )  else:    init_list=[init_list[i:i+2] for I in range (0,len (init_list), 2)]    #将列表分解为列表长度除以2个列表    max_init _list = []    #用于合并求最大值的列表 for    _list in init_list:    #将各各个子问题的求解列表合并      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)

Hopefully this article will help you with Python programming.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.