This is the python Binary Search code and when I run it doesn't work.
# 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.")
The error is like this:
TypeError: BinarySearch() missing 2 required keyword-only arguments: 'key' and 'size' So, What's wrong with it?Please help:)
There are multiple errors in your program.
You have to place the *args and **args after the positional and keyword arguements.
Lets say you have modified the function definition. Now it will convert the array into a tuple which won't work either as per your algo.it wil convert the list to tuple of lists.
def BinarySearch( key, size,*args):
pass
[] -> ([], )
3.So, you need to place only the array part.Refer the below code.
# 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.")