简体   繁体   English

python返回none而不是True / False

[英]python return none instead of True/False

I have two programs for searching using binary search in Python 我有两个用于在Python中使用二进制搜索进行搜索的程序

Program 1: 程序1:

def bin(alist,x):
    if len(alist)==0:
        return False
    else:
        mid=len(alist)//2
        if (alist[mid]==x):
            return True 
        else:
            if alist[mid] < x:
                #print(alist[mid+1:],x)
                bin(alist[mid+1:],x)
            else:   
                #print(alist[:mid],x)
                bin(alist[:mid],x)

print (bin([2,3,5,8,9],8))
print (bin([2,3,5,8,9],7))

Program output: 程序输出:

None
None

Program 2: 程式2:

def bin(alist,x):
     if len(alist)==0:
        return False
     else:
        mid=len(alist)//2
        if (alist[mid]==x):
           return  True
        else:
            if alist[mid]<x:
                return bin(alist[mid+1:],x)
            else:
                return bin(alist[:mid],x)
print(bin([1,5,7,8,9],10))
print(bin([1,4,5,8,9],8))

Program output: 程序输出:

False
True

Why is it so? 为什么会这样呢?

In your program 1, only when the list is empty or the value you are searching for in the middle of the list, it would returns you boolean value, that's because you explicitly say return if len(alist)==0 and return True when it meets if (alist[mid]==x): , you have to do the same for the rest conditions as well 在程序1中,仅当列表为空或要在列表中间搜索的值时,它才会返回布尔值,这是因为您明确地说,如果len(alist)==0returnlen(alist)==0return True它满足if (alist[mid]==x):对于其余条件,您也必须这样做

def bin(alist,x):
    if len(alist)==0:
        return False
    else:
        mid=len(alist)//2
        if (alist[mid]==x):
            return True 
        else:
            if alist[mid] < x:
                #print(alist[mid+1:],x)
                bin(alist[mid+1:],x)   # -------> return 
            else:   
                #print(alist[:mid],x)
                bin(alist[:mid],x)  # -------> return 

When you invoke your bin() method recursively and expect a boolean value, you have to add return in the above highlighted lines. 当您递归调用bin()方法并期望一个布尔值时,您必须在上述突出显示的行中添加return。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM