Search code examples
pythonalgorithmdata-structuresbinary-search

Why can't I set default parameters to a recursive binary search function?


I'm reading a book about Data Structs and algorithms in Python, and it contains an example of a binary search function and I realized something...the function takes 4 parameters, but the last two will always be the same, that is, low=0 and high=len(data). Why can't I just set them as default parameters?

The main problem here is that setting low=0 is fine, but high=len(data) will raise an error because obviously data list is being accessed before being assigned a value. So, is there a way for the function to get the low and high values itself so I don't have to pass them as args for the main call (as the recursions require them nonetheless)?

def binary_search(data, target, low, high):
    """If target is found in indicated portion of a list, returns True
    The search only considers the portion from data[low] to data[high] inclusive."""

    if low > high:
        return False
    else:
        mid = (low+high) //2

        if target == data[mid]:
            return True
        elif target < data[mid]:
            #recur on the portion left of the middle
            return binary_search(data, target, low, mid-1)
        else:
            #recur on the portion right of the middle
            return binary_search(data, target, mid+1, high)

arr = [k+1 for k in range(10000)]
binary_search(arr, 4590, 0, len(arr))

Solution

  • Yes, it does make sense to set default parameter values here.

    Since you got this from a book which is trying to teach you something about data structures, I guess they omitted that to make it easier to understand.

    As you wrote, you cannot know what the default high should be, but you dont have to. Just use None instead - that is a good default here:

    def binary_search(data, target, low=0, high=None):
        """If target is found in indicated portion of a list, returns True
        The search only considers the portion from data[low] to data[high] inclusive."""
    
        if high is None:
            high = len(data)
    
        # the rest remains the same