TypeError: ‘list‘ object is not callable

def binary_search(Li, val):
    left = 0
    right = len(Li) - 1
    while left <= right:
        mid = (left + right) // 2
        if Li(mid) == val:
            return mid
        elif Li[mid] > val:
            right = mid - 1
        elif Li[mid] < val:
            left = mid + 1
    else:
        return None
test = [1,2,3,4,5,6]
print(test)
print(binary_search(test, 3))

原因是第6行,数组的索引表示出错了,应该改为:

def binary_search(Li, val):
    left = 0
    right = len(Li) - 1
    while left <= right:
        mid = (left + right) // 2
        if Li[mid] == val:
            return mid
        elif Li[mid] > val:
            right = mid - 1
        elif Li[mid] < val:
            left = mid + 1
    else:
        return None
test = [1,2,3,4,5,6]
print(test)
print(binary_search(test, 3))

猜你喜欢

转载自blog.csdn.net/weixin_44843629/article/details/113779797