Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

binary search algorithm python

def binarySearch(array, target): #returns the index or the target 
    low = array[0]
    high = array[len(array)-1]
    if array[0] == target:
            return 0
    elif array[len(array)-1] == target:
        return len(array)-1
    else:
        while(low <= high):
            mid = int((low+high)/2)
            if array[mid]==target:
                return mid
            elif array[mid] > target:
                high = mid -1
            elif array[mid] < target:
                low = mid +1
        return -1  #returns -1 if the target does not exist
Comment

Python binary search algorithm

def binary_search(arr, x):
    low = 0
    high = len(arr) - 1
    mid = 0

    while low <= high:
        mid = (high + low) // 2
		
		// if index of the arr given by the mid isnt matching x,
		// Keep adding, else subtract one in order to get the correct mid
		// value.

        if arr[mid] < x:
            low = mid + 1
		
        elif arr[mid] > x:
            high = mid - 1
        
        else:
            return mid
    return -1

arr = [ 2, 3, 4, 10, 40 ]
x = 2

result = binary_search(arr, x)
if result != -1:
    print("Element is presented at index" , str(result))
else:
    print("Element is not presented in array")
Comment

python binary search

#blog.icodes.tech
def binary_search(item,my_list):
    found=False
    first=0
    last=len(my_list)-1
    while first <=last and found==False:
        midpoint=(first+last)//2
        if my_list[midpoint]==item:
            found=True
        else:
            if my_list[midpoint]<item:
                first=midpoint+1
            else:
                last=midpoint-1
    return found
Comment

python binary search

from bisect import bisect_right, bisect_left

'right border index := index of leftmost value > x'
bisect_right(arr, x)  # may be equal to len(arr)

'left border index := index of rightmost value < x'
bisect_left(arr, x) - 1  # may be equal to -1

def first_occurence(a, x):  # equal to a.index(x) but faster
    'Locate the leftmost value = x'
    i = bisect_left(a, x)
    if i == len(a) or a[i] != x:
        raise ValueError
    return i

def last_occurence(a, x):
    'Locate the rightmost value = x'
    i = bisect_right(a, x) - 1
    if i == -1 or a[i] != x:
    	raise ValueError
    return i
Comment

python binary search

def binary_search(l : list, z : int) -> int: # z = the value being searched
	front = 0
	rear = len(l) - 1
	mid = (front + rear) // 2
	while front <= rear and l[mid] != z:
    	if l[mid] > z:
        	rear = mid - 1
    	else:
        	front = mid + 1
    	mid = (front + rear) // 2
	return mid if l[mid] == z else -1
Comment

binary search in python

def binary_search_recursive(list_of_numbers, number, start=0, end=None):

    # The end of our search is initialized to None. First we set the end to the length of the sequence.
    if end is None:
        end = len(list_of_numbers) - 1

    if start > end:
        # This will happen if the list is empty of the number is not found in the list.
        raise ValueError('Number not in list')

    mid = (start + end) // 2  # This is the mid value of our binary search.

    if number == list_of_numbers[mid]:
        # We have found the number in our list. Let's return the index.
        return mid

    if number < list_of_numbers[mid]:
        # Number lies in the lower half. So we call the function again changing the end value to 'mid - 1' Here we are entering the recursive mode.



        return binary_search_recursive(list_of_numbers, number, start, mid - 1)
    # number > list_of_numbers[mid]
    # Number lies in the upper half. So we call the function again changing the start value to 'mid + 1' Here we are entering the recursive mode.

    return binary_search_recursive(list_of_numbers, number, mid + 1, end)
Comment

binary search in python

def binary_search(group, suspect):
  group.sort()
  midpoint = len(group)//2
  while(True):
    if(group[midpoint] == suspect):
      return midpoint
    if(suspect > group[midpoint]):
            group = group[midpoint]
    if(suspect < group[midpoint]):
      group = group[0: midpoint]
    midpoint = (len(group)//2)
Comment

PREVIOUS NEXT
Code Example
Python :: argparse list 
Python :: find max value index in value count pandas 
Python :: python voice recognition 
Python :: how to add row in spark dataframe 
Python :: how to rotate plot in jupyter 
Python :: how to change canvas background color in python tkinter 
Python :: remove blank spaces from a list python 
Python :: autopy in python install 
Python :: python list of all tkinter events 
Python :: Basic method of Converting List to Dataframe 
Python :: set jupyer color to dark 
Python :: python for loop max iterations 
Python :: get classification report sklearn 
Python :: how to fill missing values dataframe with mean 
Python :: sin and cos in python 
Python :: You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. 
Python :: remove character python 
Python :: python trick big numbers visualisation 
Python :: python copy file to new filename 
Python :: how to write your first python program 
Python :: how to access variable from another function in same class in python 
Python :: pandas dataframe select last n columns 
Python :: flask mail 
Python :: get a list of ids from queryset django 
Python :: django template for range 
Python :: np.array average row 
Python :: check if back is pressed python 
Python :: discord.py check if message has certain reaction 
Python :: python solve equation with two variables 
Python :: python random real 
ADD CONTENT
Topic
Content
Source link
Name
1+3 =