zoukankan      html  css  js  c++  java
  • python-使用递归实现二分法

    在上一篇中简单介绍了递归的使用,请戳这里 。  在此篇中,主要介绍如何用递归实现二分法。

    在使用二分法之前,首先要有个前提,那就是这个数组必须是有序数组。主要的思路为:

       ①先取出数组中的一个中间值, 和我们需要找的数字进行对比,如果恰好相等,则说明找到该数字,如果数组的中间值大于需要查找的数组,接下来的查找范围就为中间值之前的数组。反之为中间值之后的数组

        ②对数组不断的缩小范围,最后当数组中只有一个数字时,再进行比较,如果相等,则找到,否则需要查找的数字就不在我们的数组中。

    代码如下:

    def binary_search(data_source, find_number):
        """定义二分法"""
        mid = int(len(data_source)/2)                    #先取数组中的中间值
        if len(data_source) > 1:                         #判断整个数组中的数字个数
            if data_source[mid] > find_number:
                print('data is left of %s' % data_source[mid])
                binary_search(data_source[:mid], find_number)
            elif data_source[mid] < find_number:
                print('data is right of %s' % data_source[mid])
                binary_search(data_source[mid:], find_number)
            else:
                print('find the number %s' % find_number)
        elif len(data_source) == 1:                      #如果没有这个判断,当只剩一个数字时,会进入死循环
            if data_source[mid] == find_number:
                print('find the number %s' % find_number)
            else:
                print('not find the number')
                
    if __name__ == '__main__':
        data = list(range(1, 8, 2))                      #一个包含为[1, 3, 5, 7]的有序列表
        number = 1          
        binary_search(data, number)
                                            
    -----结果-----
    data is left of 5
    data is left of 3
    find the number 1
    

      

  • 相关阅读:
    boxcox1p归一化+pipeline+StackingCVRegressor
    rt-thread调度锁与关闭中断深度探究
    树莓派4最小化安装Linux
    树莓派4可以不用SD卡启动
    树莓派JTAG详细使用笔记
    树莓派上玩街机游戏
    用树莓派制作红白游戏机
    树莓派4上使用uboot+tftp调试rt-thread程序
    在window上搭建树莓派4b的RT-Thread开发环境2
    树莓派上运行RT-Thread并通过esp8266连接网络
  • 原文地址:https://www.cnblogs.com/nizhihong/p/8043062.html
Copyright © 2011-2022 走看看