I have an interative function that takes in a sequence of integers and returns the index position of a target item or returns where the target should be inserted.( if the item is not in the list )
The function works great but I am trying to figure out what is the leanest way to change this function from iterative to recursive implimentation without the aid of any auxilliary functions.
def binary_search(a_list, first, last, target):
"""a sequence of integers, index of first item, index of last item, target to search for """
while first <= last:
middle = (first + last) // 2
if a_list[middle] == target:
return middle
if target < a_list[middle]:
last = middle - 1
else:
first = middle + 1
return first
print(binary_search([2, 5, 8, 11, 17], 0, 4, 5))
How about this:
def binary_search_recursive(a_list, first, last, target):
middle = (first + last) // 2
number = a_list[middle]
if first > last:
return first
if number == target:
return middle
if target < number:
return binary_search_recursive(a_list, first, middle-1, target)
else:
return binary_search_recursive(a_list, middle+1, last, target)
EDIT : there was a small bug in the code -- now corrected.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.