Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

recursive binary search 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 :: python tableau 
Python :: bubblesort python 
Python :: if df[col].unique()==2 
Python :: convert excel to pdf python 
Python :: python template strings 
Python :: python integer to string format 
Python :: concatenating strings in python 
Python :: seaborn and matplotlib python 
Python :: django fixtures. To loaddata 
Python :: why pytest return No ModuleError 
Python :: dict_keys to list 
Python :: Insert list element at specific index 
Python :: python dictionary with list 
Python :: change python from 3.8 to 3.7 
Python :: find if value exists in dictionary python 
Python :: Python how to search in string 
Python :: Math Module degrees() Function in python 
Python :: django test imagefield 
Python :: python logging level 
Python :: zip lists 
Python :: python dict in dict 
Python :: how to use a for loop in python 
Python :: streamlit - Warning: NumberInput value below has type int so is displayed as int despite format string %.1f. 
Python :: cronometro python tkinter 
Python :: pdf to excel conversion using python 
Python :: list all placeholders python pptx 
Python :: ValueError: Please provide a TPU Name to connect to. site:stackoverflow.com 
Python :: Example code of while loop in python 
Python :: 1 12 123 python 
Python :: how to sort in python 
ADD CONTENT
Topic
Content
Source link
Name
9+2 =