0
votes

I'm a newbie and have a problem with debugging this code, I really don't know what's wrong. Help Please. This code supposed to return True if the item is in the list but it returns False instead.

def find_item(list, item):
  #Returns True if the item is in the list, False if not.
  if len(list) == 0:
    return False

  #Is the item in the center of the list?
  middle = len(list)//2
  if list[middle] == item:
    return True

  #Is the item in the first half of the list? 
  if item < list[middle]:
    #Call the function with the first half of the list
    return find_item(list[:middle], item)
  else:
    #Call the function with the second half of the list
    return find_item(list[middle+1:], item)

  return False

#Do not edit below this line - This code helps check your work!
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

the results are all False, I really need help

2
Because such algorithms are supposed to work on sorted lists, and your list_of_names is not. - Thierry Lathuille
Ok, I'll try to sort the list. Thanks for the response. - tujuh tujuh

2 Answers

1
votes

The list is not sorted. Add list.sort()

0
votes

Before finding the item sort first.

def find_item(list, item):
  list.sort()
  #Returns True if the item is in the list, False if not.
  if len(list) == 0:
    return False
  ....