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)
Related
This question already has an answer here:
Why Python recursive function returns None [duplicate]
(1 answer)
Closed 2 years ago.
I have a recursive function, I have no idea why the result printed in main is always None.
def find_nega(A: list, start: int, right: int) -> int :
s = start
r = right
mid = (s + r) // 2
if (s >= r):
return None
if (A[mid] == 0):
return mid - 1
if (A[s] < 0 and A[r] >= 0 and s == r - 1):
print(s)
return s
if (A[mid] < 0):
s = mid
find_nega(list1, s, r)
elif (A[mid] > 0):
r=mid
find_nega(list1, s,r)
else:
return mid
if __name__ == "__main__":
list1 = [-3,-2,-1,4,5,6]
x = find_nega(list1, 0, len(list1) - 1)
print(x)
In this example, it enters the condition A[s] < 0 and A[r] >= 0 and s == r - 1 but don't know why it doesn't print 2.
It doesn't print 2 because you don't return the value when you call the recursion. Here it works
def find_nega(A: list, start: int, right: int) -> int:
print(A, start, right)
s = start
r = right
mid = (s + r) // 2
if s >= r:
return None
if A[mid] == 0:
return mid - 1
if A[s] < 0 and A[r] >= 0 and s == r - 1:
#print(s)
return s
if A[mid] < 0:
s = mid
return find_nega(list1, s, r)
elif A[mid] > 0:
r = mid
return find_nega(list1, s, r)
else:
return mid
if __name__ == "__main__":
list1 = [-3, -2, -1, 4, 5, 6]
x = find_nega(list1, 0, len(list1) - 1)
print(x)
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)
I need a little help with the code below, I have been tasked with changing the insertion sort to use the given binary search function.
def binarySearch(aList, start, end, value):
#Return the position where value is or should be inserted.
while start <= end:
mid = (start + end) // 2
if aList[mid] == value:
return mid
if value < aList[mid]:
end = mid - 1
else:
start = mid + 1
return start
def insertionSort(aList):
#Sort aList in ascending order.
for index in range(1, len(aList)):
key = aList[index]
pos = index
while pos > 0 and aList[pos - 1] > key:
aList[pos] = aList[pos - 1]
pos = pos - 1
aList[pos] = key
The code I am using to test the function is:
numbers = [71, 32, 22, 19, 18, 1, 15, 40]
insertionSort(numbers)
print(numbers)
Any help is appreciated as I am having a mind blank
def binary_search(arr, val, start, end):
if start == end: #折半到最后start和end可能会相等,递归退出条件之一
if arr[start] > val:
return start
else:
return start+1
if start + 1 == end: #折半到最后start和end相差1,递归退出条件之一
return start+1
mid = (start+end)//2
if arr[mid] < val:
return binary_search(arr,val,mid, end)
elif arr[mid] > val:
return binary_search(arr, val, start, mid)
else:
return mid #折半遇到mid值与val相等,递归退出条件之一
def insertion_sort(arr:list):
for i in range(1, len(arr)):
if arr[i] <= arr[0]:
index = 0
elif arr[i] >= arr[i-1]:
continue
else:
index = binary_search(arr[0:i],arr[i],0, i-1)
arr = arr[:index]+ [arr[i]] + arr[index:i] + arr[i+1:]
return arr
arr = [30,20,80,40,50,10,60,70,90]
insertion_sort(arr)
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.
This question already has answers here:
Why does my recursive function return None?
(4 answers)
Closed 7 months ago.
I think I did everything correctly, but the base case return None, instead of False if the value does not exists. I cannot understand why.
def binary_search(lst, value):
if len(lst) == 1:
return lst[0] == value
mid = len(lst)/2
if lst[mid] < value:
binary_search(lst[:mid], value)
elif lst[mid] > value:
binary_search(lst[mid+1:], value)
else:
return True
print binary_search([1,2,4,5], 15)
You need to return the result of the recursive method invocation:
def binary_search(lst, value):
#base case here
if len(lst) == 1:
return lst[0] == value
mid = len(lst)/2
if lst[mid] < value:
return binary_search(lst[:mid], value)
elif lst[mid] > value:
return binary_search(lst[mid+1:], value)
else:
return True
And I think your if and elif condition are reversed. That should be:
if lst[mid] > value: # Should be `>` instead of `<`
# If value at `mid` is greater than `value`,
# then you should search before `mid`.
return binary_search(lst[:mid], value)
elif lst[mid] < value:
return binary_search(lst[mid+1:], value)
Because if return nothing!
if lst[mid] < value:
binary_search(lst[:mid], value)
# hidden return None
elif lst[mid] > value:
binary_search(lst[mid+1:], value)
# hidden return None
else:
return True
You need to return from if and elif too.
def binary_search(lst, value):
#base case here
if len(lst) == 1:
return lst[0] == value
mid = len(lst) / 2
if lst[mid] < value:
return binary_search(lst[:mid], value)
elif lst[mid] > value:
return binary_search(lst[mid+1:], value)
else:
return True
>>> print binary_search([1,2,4,5], 15)
False
Binary Search:
def Binary_search(num,desired_value,left,right):
while left <= right:
mid = (left + right)//2
if desired_value == num[mid]:
return mid
elif desired_value > num[mid]:
left = mid + 1
else:
right = mid - 1
return -1
num =[12,15,19,20,22,29,38,41,44,90,106,397,399,635]
desired_value = 41
result = Binary_search(num,desired_value,0,len(num)-1)
if result != -1:
print("Number found at " + str(result),'th index')
else:
print("number not found")
def rBinarySearch(list,element):
if len(list) == 1:
return element == list[0]
mid = len(list)/2
if list[mid] > element:
return rBinarySearch( list[ : mid] , element )
if list[mid] < element:
return rBinarySearch( list[mid : ] , element)
return True
def binary_search(lists,x):
lists.sort()
mid = (len(lists) - 1)//2
if len(lists)>=1:
if x == lists[mid]:
return True
elif x < lists[mid]:
lists = lists[0:mid]
return binary_search(lists,x)
else:
lists = lists[mid+1:]
return binary_search(lists,x)
else:
return False
a = list(map(int,input('enter list :').strip().split()))
x = int(input('enter number for binary search : '))
(binary_search(a,x))
def binary_search(arr, elm):
low, high = 0, len(arr) - 1
while low <= high:
mid = (high + low) // 2
val = arr[mid]
if val == elm:
return mid
elif val <= elm:
low = mid + 1
else:
high = mid - 1
return -1
print(binary_search([2, 3, 4, 6, 12, 19, 20, 21], 12)) # 4
print(binary_search([2, 3, 4, 6, 12, 19, 20, 21], 3333)) # -1
def Binary_search(li, e, f, l):
mid = int((f+l)/2)
if li[mid] == e:
print("Found",li[mid] )
elif f == l-1 and li[mid] != e:
print("Not Found ")
elif e < li[mid]:
Binary_search(li, e, f,mid)
elif e > li[mid]:
Binary_search(li, e, mid,l)
elements = [1,2,4,6,8,9,20,30,40,50,60,80,90,100,120,130,666]
Binary_search(elements, 120, 0, len(elements))
class binar_search:
def __init__(self,arr , element):
self.arr = arr
self.element = element
def search(self):
n = len(self.arr)
low = 0
high = n-1
while(low <= high):
mid = (low+high)//2
if self.arr[mid] == self.element:
return mid
elif self.arr[mid] < self.element:
low = mid+1
else:
high = mid -1
return 0