I am reading Grokking Algorithms, which seems to be a highly recommended book. I am looking at the first algorithm for "binary search" and the guy uses two "ifs" instead of a "if" and "elif". Would using two "ifs" be better or faster?
def binary_search(list, item):
    low = 0
    high = len(list) - 1
    while low <= high:
        mid = (low + high)
        guess = list[mid]
        if guess == item:
            return mid
        if guess > item:
            high = mid - 1
        else:
            low = mid + 1
    return None
my_list = [1,3,5,7,9]
example1
>>> def foo():
    a = 10
    if a == 10:
        print("condition1")
    elif a == 10:
        print("condition2")
    else:
        print(0)    
>>> foo()
condition1
>>> 
elif is guaranteed not to run when if is true.
example2
def foo():
    a = 10
    if a == 10:
        print("condition1")
    if a == 10:
        print("condition2")
    else:
        print(0)
>>> foo()
condition1
condition2
>>> 
example3 modify if statement of example2.
if a == 10:
    print("condition1")
    return a
output
>>> foo()
condition1
10
So, in your case adding a return in first if statement has similar operation like an if-elif block. the (return a) is preventing the second if statement to be executed in example3.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With