Search code examples
pythonrecursionargumentsbinary-search

In Python can you pass two arguments to a function where one argument is extrapolated from the other?


I'm writing a recursive binary-search function in Python. My code looks like common examples where the function accepts:

(a) a list of numbers; (b) the search term; (c) the length of the list for the initial location of the right pointer; and (d) a default argument of 0 for the left pointer.

Do I have to pass both a list of numbers (a) and also the length of the list (c)? Can't I make a default argument that automatically computes the length of argument (a)?

MWE:

def binarySearchRecur(nums, target, high, low=0):
    if high - low == 1:
        return "not found"
    elif nums[(high + low) // 2] < target:
        low = (high + low) // 2
        return binarySearchRecur(nums, target, low, high)
    elif nums[(high + low) // 2] > target:
        high = (high + low) // 2 + 1
        return binarySearchRecur(nums, target, low, high)
    return f"index at: {(low + high) // 2}"


target = 16
nums = [x for x in range(20)]
print(binarySearchRecur(nums, target, len(nums)-1))

In the code above I'd like to call the function the first time using only nums and target.


Solution

  • Could you simply do something like this?

    def binarySearchRecur(nums, target, high=None, low=0):
       if high is None:
          high=len(nums)
    ...
    

    This way if you only input the list and the target, the first thing the function will do is to infer "high" from the list.