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)
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)
The main idea is:
searchindex() - repeat binary search algorithm over the list of random data with looking back and with fix.(variable counter1 should save number of occurences)
occur() - just assumning total number of occurences.
Please help to find a problem.
I always get counter1 = 0 after running a code.
def searchindex(searchlist, secs, x):
ts = calendar.timegm(time.gmtime())
delta_minute_ts = (ts - (ts % 60)) - secs
last_minute = datetime.datetime.fromtimestamp(delta_minute_ts).strftime('%Y-%m-%d %H:%M')
start = 0
end = len(searchlist) - 1
counter1 = 0
while (start <= end):
mid = (start + end) // 2
if (searchlist[mid] == last_minute):
counter1 = int(mid)
if x == 1:
end = mid - 1
else:
start = mid + 1
elif (last_minute < searchlist[mid]):
end = mid - 1
else:
start = mid + 1
return counter1
def occur():
start_result = searchindex(new1, 60, 1)
end_result = searchindex(new1, 60, 2)
if start_result is None:
return 'no results'
else:
end_result - start_result + 1
I am using various search algorithm and I want to use it on data frame using other column here is the code.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import time as t
def linear_search(arr, x):
for i in range(len(arr)):
# comparing the array against the given parameter
if arr[i] == x:
# Return the parameter if the paramerS is true
return x
return -1;
def linear_search_while(arr,x):
found = -1
i = 0
while i < len(arr) and found == -1:
if arr[i] == x:
return x
i = i + 1
return -1
def binary_search_while(alist, item):
first = 0
last = len(alist)-1
found = -1
while first<=last and not found:
midpoint = (first + last)//2
if alist[midpoint] == item:
found = item
else:
if item < alist[midpoint]:
last = midpoint-1
else:
first = midpoint+1
return found
def binary_search_rec(arr, x):
if len(arr) == 0 or (len(arr) == 1 and arr[0]!= x):
return -1
mid = arr[len(arr)// 2]
if x == mid: return x
if x < mid: return binary_search_rec(arr[:len(arr)// 2], x)
if x > mid: return binary_search_rec(arr[len(arr)//2+1:], x)
def selectionSort(a):
len_a = len(a) # getting the length of the array
for i in range (0,len_a-1):
minIndex = i
for j in range(i+1, len_a):
array
if a[j] < a[minIndex]:
minIndex = j
temp = a[i]
a[i] = a[minIndex]
a[minIndex] = temp
return a
def timer_Linear_Search(arr, x):
arr = selectionSort(arr)
start = t.clock()
linear_search_while(arr,x)
stop = t.clock()
timer = stop - start
return timer
def timer_Binary_Search(arr, x):
arr = selectionSort(arr)
start = t.clock()
binary_search_while(arr,x)
stop = t.clock()
timer = stop - start
return timer
def timer_Sort(arr):
start = t.clock()
selectionSort(arr)
stop = t.clock()
timer = stop - start
return timer
def timer_Linear_S_Search(arr, x):
start = t.clock()
arr = selectionSort(arr)
linear_search_while(arr,x)
stop = t.clock()
timer = stop - start
return timer
def timer_Binary_S_Search(arr, x):
start = t.clock()
arr = selectionSort(arr)
binary_search_while(arr,x)
stop = t.clock()
timer = stop - start
return timer
calculation_df = pd.DataFrame()
calculation_df['Size'] = [512,1024, 2048,4096,8192]
*I want to use all the above functions such that they use thev value of Size and create a random array and number to calculate the rest of the columns.
[The final data should look something like this][1]
currently i am using manual calculation and appending the data to the dataframe
My question is how can I apply custom function in python code
I am currently manually adding all these calculation to the dataframe*
You can use the apply method of DataFrame (see this):
def linear_search(arr, x):
for i in range(len(arr)):
if arr[i] == x:
return x
return -1;
df = pd.DataFrame(data=[[1,2],[3,4],[5,6]], columns=["a", "b"])
df.apply(lambda arr: linear_search(arr, 1))
Output:
a 1
b -1
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