1

I'm switching over to Python and am practicing some basic logic flows, and I wrote a binary search function. Is there a more elegant way to write this? I don't like how I set the initial maxim to 10**99 for example (that was just a way to encompass any realistic list size).

def binary_search(val, arr, minum=0, maxim=10**99):
    if val < arr[0] or val > arr[-1]:
        return "Not in range"

    arr = arr[minum:maxim]
    middle = int(len(arr) / 2)
    maxim = len(arr)

    if val == arr[middle]:
        return middle
    elif val > arr[middle]:
        return middle + binary_search(val, arr, middle, maxim)
    else:
        return binary_search(val, arr, 0, middle)
3
  • Have you seen this: interactivepython.org/runestone/static/pythonds/SortSearch/… Commented Feb 9, 2017 at 23:19
  • 2
    This question might be better suited for Code Review than Stack Overflow. Commented Feb 9, 2017 at 23:20
  • You may have a logical error in your else statement. Should the line not be return binary_search(val, arr, minum, middle), symmetrical with your elif branch? Commented Feb 9, 2017 at 23:20

1 Answer 1

1

If maxim is going to only be used in a slice, None does the same thing:

def binary_search(val, arr, minum=None, maxim=None):

See:

>>> x = [1, 2, 3, 4, 5]
>>> x[None:None]
[1, 2, 3, 4, 5]
>>> x[1:None]
[2, 3, 4, 5]
>>>

But honestly, it seems like a useless parameter unless you want to limit the search, but then you might as well do that explicitely before you when you pass the list (not array!) in.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.