126k views
3 votes
The find_item functions uses binary search to recursively locate an item is the list, returning true if found, false otherwise. Something is missing from this function. Can you spot what it is and fix it. Add debug lines where appropriate, to help narrow the problem.

1 Answer

2 votes

Answer:

def find_item(listed, item):

listed.sort()

#Returns True if the item is in the list, False if not.

if len(listed) == 0:

return False

middle = int(len(listed)/2)

#Is the item in the first half of the list?

if item < listed[middle]:

#Call the function with the first half of the list

return find_item(listed[:middle], item)

#Is the item in the center of the list?

if listed[middle] == item:

return True

else:

#Call the function with the second half of the list

return find_item(listed[middle+1:], item)

return False

list_of_names = ["Parker", "Drew", "Cameron", "Logan", "Alex", "Chris", "Terry", "Jamie", "Jordan", "Taylor"]

print(find_item(list_of_names, "Alex")) # True

print(find_item(list_of_names, "Andrew")) # False

print(find_item(list_of_names, "Drew")) # True

print(find_item(list_of_names, "Jared")) # False

Step-by-step explanation:

The defined python function is used to implement a binary search, the function is recursively called in the function statement, but for it to work on the list ( ie, search for an item in the list), the list must be sorted in ascending order (default).

User Rohatgisanat
by
5.3k points