tujuh tujuh
tujuh tujuh

Reputation: 1

Why are this recursive bisection python code not working

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

Upvotes: 0

Views: 3616

Answers (2)

ArunSK
ArunSK

Reputation: 341

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

Upvotes: 0

Ajith Sankar
Ajith Sankar

Reputation: 11

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

Upvotes: 1

Related Questions