0

这是 python 二进制搜索代码,当我运行它时它不起作用。

# Binary Search

def BinarySearch(*args, key, size):
    low = 0
    high = size - 1
    while low <= high:
        mid = (low + high) / 2
        if key < args[mid]:
            high = mid - 1
        else:
            if key > args[mid]:
                low = mid + 1
            else:
                return mid + 1
    return -1

arraySize = 10
A = [num * 2 for num in range(10)]
print("Numbers in array are : ", A)
searchKey = input("Enter integer search key : ")
element = BinarySearch(A, searchKey, arraySize)
if element != -1:
    print("Found value in element : ", element)
else:
    print("Value not found.") 

错误是这样的:

TypeError: BinarySearch() 缺少 2 个必需的仅关键字参数:'key' 和 'size' 那么,它有什么问题?请帮助:)

4

2 回答 2

0

改变这个

element = BinarySearch(A, searchKey, arraySize)

element = BinarySearch(A, key=searchKey, size=arraySize)
于 2020-03-25T15:12:43.510 回答
0

您的程序中有多个错误。

  1. 您必须将 *args 和 **args 放在位置和关键字争论之后。

  2. 假设您已经修改了函数定义。现在它将数组转换为一个元组,根据您的算法也不起作用。它将列表转换为列表元组。

        def BinarySearch( key, size,*args):
              pass
    
        [] -> ([], )   
    

3.所以,你只需要放置数组部分。参考下面的代码。

    # Binary Search

def BinarySearch(arr, key, size):
    print(args)
    low = 0
    high = size - 1
    while low <= high:
        mid = (low + high) // 2
        if key < args[mid]:
            high = mid - 1
        else:
            if key > args[mid]:
                low = mid + 1
            else:
                return mid + 1
    return -1

arraySize = 10
A = [num * 2 for num in range(10)]
print("Numbers in array are : ", A)
searchKey = input("Enter integer search key : ")
element = BinarySearch(A, int(searchKey), arraySize)
if element != -1:
    print("Found value in element : ", element)
else:
    print("Value not found.") 
于 2020-03-25T15:16:26.257 回答