Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

binary search recursive python

"""Binary Search
Recursive
	- 2 Separate functions
    	--> Perhaps more readable?
    - Or just one function that recursively calls itself
		--> Perhaps more logical?
"""

## With 2 separate functions
def bin_recur(lst, item):
    return go_bin_recur(lst, item, 0, len(lst) - 1)
    
def go_bin_recur(lst, item, low, high):
    if low <= high:
        mid = (low + high) // 2
        if item > lst[mid]: # To the left
            low = mid + 1 
        elif item < lst[mid]: # To the right
            high = mid - 1
        else: # Found
            return mid
        return go_bin_recur(lst, item, low, high)
    return [] # Not found


## With one function
def bin_recur(lst, item, low=0, high=None):
    if high is None:
        high = len(lst) - 1
    if low <= high:
        mid = (low + high) // 2
        if item > lst[mid]: # To the left
            low = mid + 1 
        elif item < lst[mid]: # To the right
            high = mid - 1
        else: # Found
            return mid
        return bin_recur(lst, item, low, high)
    return [] # Not found

"""Whats your preference?"""
Comment

PREVIOUS NEXT
Code Example
Python :: join in pathlib path 
Python :: string concatenation in python 
Python :: python3 format leading 0 
Python :: Python Regex Backslash “” 
Python :: append dictionary python 
Python :: how to use information from env variables in python 
Python :: adding two strings together in python 
Python :: concatenate list in python 
Python :: add favicon in django admin 
Python :: prevent selenium from closing 
Python :: python iterate over string 
Python :: what is iteration in python 
Python :: how to submit two forms in django 
Python :: python how to delete a variable 
Python :: python logging variables extra 
Python :: list in python 
Python :: insert row in dataframe pandas 
Python :: convert number to reversed array of digits python 
Python :: pandas read csv specify column dtype 
Python :: python day of the year 
Python :: How to get historical klines python binance 
Python :: append to list in dict python 
Python :: how to join basename and directory in python os 
Python :: calculate area under the curve in python 
Python :: log in python 
Python :: django-admin startproject 
Python :: find occerences in list python 
Python :: define a string in python 
Python :: pd df replace 
Python :: selenium proxy with authentication 
ADD CONTENT
Topic
Content
Source link
Name
9+5 =