recursion binary search in a list of names - python

I am trying to build a function that gets the index of an item form a list
names = [('Daisy','Fox'),('Josh','Belluga'),('Elin','Grosefield'),('Mike','Levinsan')]
this is the code
def find_name(lst,name,low,high):
if low >= high:
return None
middle = (low + high) / 2
if lst[middle] == name:
return middle
elif name < lst[middle]:
return find_name(lst, name, low, middle)
else:
return find_name(lst, name, middle + 1, high)
it works fine and all but the only problem that im having is when I define the low and high values to be equals for the index I want to get
for example
print find_name(names,('Josh','Belluga'),0,1)
returns none when it should return 1 for some reason

def find_name(lst,name,low,high):
if high is None:
high = len(lst) - 1
if low > high:
return False
middle = (low + high) / 2
if lst[middle] == name:
return middle
elif name < lst[middle]:
return find_name(lst, name, low, middle-1)
else:
return find_name(lst, name, middle + 1, high)
names = [('Daisy','Fox'),('Josh','Belluga'),('Elin','Grosefield'),('Mike','Levinsan')]
print find_name(names, ('Josh','Belluga'), 0, 1)
Here is what you are looking for. Just compare your original code with this and you will see what you did wrong.

Related

How does the return work inside a recursive function in Python?

I am having issues when returning the values from a recursive function. For example, in a very simple function called 'RBinSearch', I am trying to find the index of the key in an array. Unfortunately, I just cannot able to return the value (answer should be 4) based on my understanding.
For comparison, I have used a normal function with a loop to test the return (in a function called 'BinarySearch' here), which is working as expected. Can anyone please explain how the return behave inside a recursive function and where my understanding is incorrect? Thanks!
import math
import sys
def BinarySearch(array, key):
low=0
high=len(array)-1
while(low<=high):
mid=math.floor((low+high)/2)
if(key==array[mid]):
return mid
elif(key<array[mid]):
high=mid-1
elif(key>array[mid]):
low=mid+1
return -1
def RBinSearch(array,low,high,key):
if(low<=high):
mid=math.floor((low+high)/2)
print("Value of mid: ",mid)
if(key==array[mid]):
print("Found the value: ",mid)
return mid
sys.exit()
elif(key<array[mid]):
RBinSearch(array, low, mid-1, key)
else:
RBinSearch(array, mid+1, high, key)
return -1
arr=[4,8,10,15,18,21,24,27,29,33,34,37,39,41,43]
print("Index from while Bin search: ",BinarySearch(arr, 18))
print("The index found using the Binary search is: ",RBinSearch(arr, 0,len(arr)-1,18))
Output
You need to return RBinSearch result in your RBinSearch function:
def RBinSearch(array, low, high, key):
if low <= high:
mid = math.floor((low + high) / 2)
print("Value of mid: ", mid)
if key == array[mid]:
print("Found the value: ", mid)
return mid
elif key < array[mid]:
return RBinSearch(array, low, mid - 1, key)
else:
return RBinSearch(array, mid + 1, high, key)
return -1
Also you shouldn't use sys.exit().

What is wrong with this python binary search code, im getting an index error

I keep getting an index overflow error. Am i missing something?
I checked my array length again and again but i dont see where i have accessed a value which does not exist
def binary_search_helper(arr,val,low,high):
mid = low + ((low+high)//2)
if low >= high:
return("Not F")
elif val==arr[mid] :
return (arr[mid])
elif val<=arr[mid]:
return( binary_search_helper(arr, val, low, mid-1))
else:
return( binary_search_helper(arr, val, mid+1, high))
def binary_search(arr,val):
return binary_search_helper(arr, val, 0, len(arr)-1)
if __name__=="__main__":
arr=[0,1,2,3,4,5]
val=3
ans= binary_search(arr,val)
print(ans)
There are several mistakes, you can look what I changed here:
def binary_search_helper(arr,val,low,high):
mid = (low+high)//2
if val==arr[mid] :
return (arr[mid])
elif low >= high:
return("Not F")
elif val<=arr[mid]:
return( binary_search_helper(arr, val, low, mid-1))
else:
return( binary_search_helper(arr, val, mid+1, high))

How to compute the number of steps in binary search?

This code returns only the position of the target.
I need to compute number of steps also.
How can I modify this code to achieve my goal?
def binary_search(arr, low, high, x):
if high >= low:
mid = (high + low) // 2
if arr[mid] == x:
return mid
elif arr[mid] > x:
return binary_search(arr, low, mid - 1, x)
else:
return binary_search(arr, mid + 1, high, x)
else:
return -1
LT = [1,2,3,4,5,6,7,8,9,10]
pos = binary_search(LT,0,9,5)
print(str(pos))
You could add it as a function parameter and update recursively
def binary_search(arr, low, high, x, steps = 0):
if high >= low:
mid = (high + low) // 2
if arr[mid] == x:
print(f"found at {steps} steps")
return mid
elif arr[mid] > x:
return binary_search(arr, low, mid - 1, x, steps + 1)
else:
return binary_search(arr, mid + 1, high, x, steps + 1)
else:
return -1
Binary search code in Python without recursion :
def binary_search_itr(arr, size, val,step=0):
ln=0
r = size-1
mid = (ln + r) // 2
while (arr[mid] != val and ln <= r):
if val < arr[mid]:
step = step + 1
r = mid - 1
else:
step = step + 1
ln = mid + 1
mid = (ln + r) // 2
if arr[mid] == val:
step = step + 1
return mid,step
return -1
LT = [1,2,3,4,5,6,7,8,9,10]
pos = binary_search_itr(LT,9,9)
print(pos)

Python - no boolean display at the terminal

I am studying algorithms with Python and currently working on recursive and iterative binary search, I think the code is correct.
When I launch the program from the terminal I do not have any output.
It should return True twice, one from the iterative function and the other one from the recursive function but it doesn't display any boolean.
mbp-de-mathieu:programmation Mathieu$ cd python/
mbp-de-mathieu:python Mathieu$ python3.8 hello.py
coucou mathieu
mbp-de-mathieu:python Mathieu$ python3.8 binary_search.py
However I can get down in the console after the program call by using enter. Could someone explain to me what is happening? I am using a Mac.
data = [2,4,5,7,8,9,12,14,17,19,22,25,27,28,33,37]
target = 25
def linear_search(data, target):
for i in range(len(data)):
if data[i] == target:
return True
return False
def binary_search_iterative(data, target):
low = 0
high = len(data) - 1
while low <= high:
mid = (low + high) // 2
if target == data[mid]:
return True
elif target < data[mid]:
high = mid - 1
else:
high = mid + 1
return False
def binary_search_recursive(data, target, low, high):
if low > high:
return False
else:
mid = (low + high) // 2
if target == data[mid]:
return True
elif target < data[mid]:
return binary_search_recursive(data, target, low, mid-1)
else:
return binary_search_recursive(data, target, mid+1, high)
print(binary_search_iterative(data, target))
print(binary_search_recursive(data, target, 0, len(data)-1))
Thank you in advance
Wishing you a nice weekend
Best Regards
Mathieu

What's wrong with this code for BinarySearch?

This is the python Binary Search code and when I run it doesn't work.
# Binary Search
def BinarySearch(*args, key, size):
low = 0
high = size - 1
while low <= high:
mid = (low + high) / 2
if key < args[mid]:
high = mid - 1
else:
if key > args[mid]:
low = mid + 1
else:
return mid + 1
return -1
arraySize = 10
A = [num * 2 for num in range(10)]
print("Numbers in array are : ", A)
searchKey = input("Enter integer search key : ")
element = BinarySearch(A, searchKey, arraySize)
if element != -1:
print("Found value in element : ", element)
else:
print("Value not found.")
The error is like this:
TypeError: BinarySearch() missing 2 required keyword-only arguments: 'key' and 'size'
So, What's wrong with it?Please help:)
There are multiple errors in your program.
You have to place the *args and **args after the positional and keyword
arguements.
Lets say you have modified the function definition. Now it will convert
the array into a tuple which won't work either as per your
algo.it wil convert the list to tuple of lists.
def BinarySearch( key, size,*args):
pass
[] -> ([], )
3.So, you need to place only the array part.Refer the below code.
# Binary Search
def BinarySearch(arr, key, size):
print(args)
low = 0
high = size - 1
while low <= high:
mid = (low + high) // 2
if key < args[mid]:
high = mid - 1
else:
if key > args[mid]:
low = mid + 1
else:
return mid + 1
return -1
arraySize = 10
A = [num * 2 for num in range(10)]
print("Numbers in array are : ", A)
searchKey = input("Enter integer search key : ")
element = BinarySearch(A, int(searchKey), arraySize)
if element != -1:
print("Found value in element : ", element)
else:
print("Value not found.")
Change this
element = BinarySearch(A, searchKey, arraySize)
to
element = BinarySearch(A, key=searchKey, size=arraySize)

Categories