I am currently practicing binary search and I'm having trouble understanding the difference in syntax between lo == 0, hi == len(cards) - 1
and lo, hi = 0, len(cards) - 1
. The code works with the second method but not with the first one. Any help would be appreciated. Thank you.
The code is as follows:
def binary_search(cards, query):
# lo == 0, hi == len(cards) - 1
lo, hi = 0, len(cards) - 1
while lo <= hi:
mid = (lo+hi) // 2
result = locate_card(cards, query, mid)
mid_card = cards[mid]
print('lo: ', lo, 'hi: ', hi)
print('mid: ', mid)
print('mid_card: ', mid_card)
print('result: ', result)
print('\n')
if result == 'found':
return mid
elif result == 'left':
hi = mid - 1
else:
lo = mid + 1
return -1
def locate_card(cards, query, mid):
if cards[mid] == query:
if mid > 0 and cards[mid-1] == query:
return 'left'
else:
return 'found'
elif cards[mid] < query:
return 'left'
else:
return 'right'
return binary_search(cards, query)
if __name__ == '__main__':
cards = [13, 11, 10, 7, 4, 3, 1, 0]
query = 1
print(binary_search(cards, query))
A double equal-sign (==
) is the operator to compare two object to see if they are equal. lo == 0, hi == len(cards) - 1
will compare lo
to 0
and hi
to len(cards)-1
.
lo, hi = 0, len(cards) - 1
is the same as writeing
lo = 0
hi = len(cards) - 1