Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Eva Feng
1,364 PointsRecursive Binary Search Python
Hi can someone tell me what is wrong with my code? It returns false, false as opposed to false, true
I know the problem is under the 3rd "else", problem is solved when I change the following
return recursive_binary_search(list[:midpoint-1], target)
into this line
return recursive_binary_search(list[:midpoint], target)
However i don't understand why the list cant start from 0 all the way to midpoint - 1
Thanks in advance
def recursive_binary_search(list, target):
if len(list) == 0:
return False
else:
midpoint = (len(list))//2
if list[midpoint] == target:
return True
else:
if list[midpoint] < target:
return recursive_binary_search(list[midpoint+1:], target)
else:
return recursive_binary_search(list[:midpoint-1], target)
def verify(result): print("Target found: ", result)
numbers = [1,2,3,4,5,6,7,8] result = recursive_binary_search(numbers, 12) verify(result)
result = recursive_binary_search(numbers, 6) verify(result)