0

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
  • 4
    Because such algorithms are supposed to work on sorted lists, and your list_of_names is not. Commented Apr 5, 2020 at 8:59
  • Ok, I'll try to sort the list. Thanks for the response. Commented Apr 5, 2020 at 9:01

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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
  ....

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.