二进制搜索的此代码有什么问题?

这是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.") 

错误是这样的:


类型错误:二进制搜索()缺少2个必需的仅关键字参数:“键”和“大小”那么,它有什么问题?请帮忙:)


qq_遁去的一_1
浏览 126回答 2
2回答

慕盖茨4494581

程序中有多个错误。您必须将 *args 和 **args 放在位置和关键字参数之后。假设您已经修改了函数定义。现在,它将数组转换为元组,该元组将按照您的 algo.it 将列表转换为列表元组也不起作用。&nbsp; &nbsp; def BinarySearch( key, size,*args):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; pass&nbsp; &nbsp; [] -> ([], )&nbsp; &nbsp;3.So,您只需要放置阵列部分。请参阅以下代码。&nbsp; &nbsp; # Binary Searchdef BinarySearch(arr, key, size):&nbsp; &nbsp; print(args)&nbsp; &nbsp; low = 0&nbsp; &nbsp; high = size - 1&nbsp; &nbsp; while low <= high:&nbsp; &nbsp; &nbsp; &nbsp; mid = (low + high) // 2&nbsp; &nbsp; &nbsp; &nbsp; if key < args[mid]:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; high = mid - 1&nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if key > args[mid]:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; low = mid + 1&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return mid + 1&nbsp; &nbsp; return -1arraySize = 10A = [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:&nbsp; &nbsp; print("Found value in element : ", element)else:&nbsp; &nbsp; print("Value not found.")&nbsp;

慕神8447489

更改此element&nbsp;=&nbsp;BinarySearch(A,&nbsp;searchKey,&nbsp;arraySize)自element&nbsp;=&nbsp;BinarySearch(A,&nbsp;key=searchKey,&nbsp;size=arraySize)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python