二进制搜索递归python

时间:2020-08-04 15:20:59

标签: python recursion binary-search

我是数据结构的新手,想问一下为什么我的二进制搜索给我一个错误。

我尝试在vsc终端中运行,并给了我一个语法错误。同时,“问题”标签未显示任何错误。将不胜感激指针!

def binarysearch(list,value):
    if list == [] or (len(list)==1 and list[0]!= value):
        return False
    else:
        mid = list[len(list)/2]
        if mid == value:
            return True
        elif mid > value:
            return binarysearch(list[:len(list)/2],value)
        else:
            return binarysearch(list[len(list)/2+1:],value)

a =[1,2,3,4,5,6,7,8]
value = 7

if binarysearch(a,value):
    print("found")
else:
    print("none")

2 个答案:

答案 0 :(得分:0)

问题出在调用递归的行中,要拆分的索引必须是整数而不是浮点数。尝试以下代码-

def binarysearch(list,value):
    if list == [] or (len(list)==1 and list[0]!= value):
        return False
    else:
        mid = list[int(len(list)/2)]
        if mid == value:
            return True
        elif mid > value:
            return binarysearch(list[:int(len(list)/2)],value)
        else:
            return binarysearch(list[int(len(list)/2)+1:],value)

a =[1,2,3,4,5,6,7,8]
value = 7

if binarysearch(a,value):
    print("found")
else:
    print("none")

答案 1 :(得分:0)

您的代码索引部分存在问题,请尝试使用//(整数除法)符号而不是除法来获得除法后的近似值,而不是十进制(浮点数):

def binarysearch(list,value):
if list == [] or (len(list)==1 and list[0]!= value):
    return False
else:
    mid = list[len(list)//2] # approximating the division to get an integer
    if mid == value:
        return True
    elif mid > value:
        return binarysearch(list[:len(list)//2],value)
    else:
        return binarysearch(list[len(list)//2+1:],value)
相关问题