def search(num_list, find):
while True:
if not num_list:
return "Not in list"
else:
i = int(len(num_list) // 2)
if int(num_list[i]) == find:
return i
elif int(num_list[i]) > find:
num_list = (lambda x: x < num_list[i], num_list)
elif int(num_list[i]) < find:
num_list = (lambda x: x > num_list[i], num_list)
checkList = [2, 5, 8, 18, 22, 35, 45, 72]
element = int(input("Enter number to be found: "))
print(search(checkList, element))
The following error message occurs when i try to run it with any number:
Traceback (most recent call last):
File "/home/rahul/PycharmProjects/binSearch/main.py", line 17, in <module>
print(search(checkList, element))
File "/home/rahul/PycharmProjects/binSearch/main.py", line 7, in search
if int(num_list[i]) == find:
TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'
So I am trying to make a python binary search algorithm for class and thought this would work fine. I have no idea why this is not working and would love an expert opinion
The reason you are getting this error, is your lambda function is in a tuple of a function and a list. So just looking at that part:
num_list = [2, 5, 8, 18, 22, 35, 45, 72]
i = 5
num_list = (lambda x: x < num_list[i], num_list)
print(num_list)
result:
(<function <lambda> at 0x107a170e0>, [2, 5, 8, 18, 22, 35, 45, 72])
which is the memory address of the lambda function, and a list, which you end up passing to int()
, giving the error that you see.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.