码迷,mamicode.com
首页 > 编程语言 > 详细

Python-函数递归-二分法

时间:2017-10-18 00:21:20      阅读:328      评论:0      收藏:0      [点我收藏+]

标签:err   class   数字   python   sts   找不到   col   逻辑   range   

l=[1,2,10,30,33,99,101,200,301,402]  #从小到大排列的数字列表

num=200
for item in l:
    if num == item:
        print(find it)
        break

此寻找数字的方法,效率低;并且如果查找402,那么最后break就没有什么意思了。

下面用二分法:(一)

l=[1,2,10,30,33,99,101,200,301,402] #从小到大排列的数字列表
def get(num,l):
        mid=len(l)//2
        if num > l[mid]:
            #in the right
            l=l[mid+1:]
        elif num < l[mid]:
            #in the left
            l=l[:mid]
        else:
            print(find it)
            return
        get(num,l)

get(200,l)

def get(num,l):
        mid=len(l)//2
        if num > l[mid]:
            #in the right
            l=l[mid+1:]
            get(num, l)
        elif num < l[mid]:
            #in the left
            l=l[:mid]
            get(num, l)
        else:
            print(find it)
            return

get(200,l)

得来!

下面开始优化,得到寻找次数,和当前的中间值(二)

l=[1,2,10,30,33,99,101,200,301,402] #从小到大排列的数字列表
def get(num,l):
        mid=len(l)//2
        print(l,l[mid])
        if num > l[mid]:
            #in the right
            l=l[mid+1:]
        elif num < l[mid]:
            #in the left
            l=l[:mid]
        else:
            print(find it)
            return
        get(num,l)

get(200,l)

问题来了,如果想要取的值不存在呢?      get(3,l)

IndexError: list index out of range
[1, 2, 10, 30, 33, 99, 101, 200, 301, 402]
[1, 2, 10, 30, 33]
[1, 2]
[]

数值不存在的情况下,列表切空了也找不到这个值。

解决方法如下:

l=[1,2,10,30,33,99,101,200,301,402] #从小到大排列的数字列表
def get(num,l):
    print(l)
    if len(l) > 0: #列表不为空,则证明还有值是可以执行二分法逻辑的
        mid=len(l)//2
        if num > l[mid]:
            #in the right
            l=l[mid+1:]
        elif num < l[mid]:
            #in the left
            l=l[:mid]
        else:
            print(find it)
            return
        get(num,l)
    else: #列表为空,则证明根本不存在要查找的值
        print(not exists)
        return
get(403,l)

 

Python-函数递归-二分法

标签:err   class   数字   python   sts   找不到   col   逻辑   range   

原文地址:http://www.cnblogs.com/guoxiangqian/p/7684506.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!