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))
CodePudding user response:
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
CodePudding user response:
The == operator is used when we want to use conditional expressions and want to compare two expressions that, if true, perform an operation, but the = operator is used to assign a value to a variable. for example:
if lo == 0 and hi == len(cards) - 1:
print("Hello")
CodePudding user response:
I suggest playing around in the python interpreter, in order to better understand the three notations =
(assignment), ==
(equality test), and ,
(used to build tuples).
Playing with ==
and ,
: equality of tuples, or tuple of equalities
>>> 3 == 3, 4 == 4
(True, True)
>>> 3, 4 == 3, 4
(3, False, 4)
>>> (3, 4) == (3, 4)
True
>>> 3 == 3 and 4 == 4
True
Playing with =
and ,
: assignment with unpacking
>>> 0, 10
(0, 10)
>>> lo, hi = (0, 1)
>>> print(lo, hi)
0 1
>>> lo, hi = 1, 2
>>> print(lo, hi)
1 2
>>> lo = 3
>>> hi = 4
>>> print(lo, hi)
3 4
Tuple of assignment: that is not correct syntax
>>> lo = 5, hi = 6
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?
Assignment expression with :=
(python >= 3.8)
>>> (lo := 7, hi := 8)
(7, 8)
>>> print(lo, hi)
7 8