我目前正在練習二進制搜索,但我無法理解 和 之間的語法lo == 0, hi == len(cards) - 1差異lo, hi = 0, len(cards) - 1。該代碼適用于第二種方法,但不適用于第一種方法。任何幫助,將不勝感激。謝謝你。
代碼如下:
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))
uj5u.com熱心網友回復:
雙等號 ( ==) 是比較兩個物件以查看它們是否相等的運算子。lo == 0, hi == len(cards) - 1將比較loto0和hito len(cards)-1。
lo, hi = 0, len(cards) - 1和寫一樣
lo = 0
hi = len(cards) - 1
uj5u.com熱心網友回復:
我建議在 python 解釋器中玩耍,以便更好地理解三個符號=(賦值)、==(相等測驗)和,(用于構建元組)。
玩==and ,:元組相等,或相等的元組
>>> 3 == 3, 4 == 4
(True, True)
>>> 3, 4 == 3, 4
(3, False, 4)
>>> (3, 4) == (3, 4)
True
>>> 3 == 3 and 4 == 4
True
玩=and ,: 拆包作業
>>> 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
賦值元組:這是不正確的語法
>>> lo = 5, hi = 6
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?
:=(python >= 3.8)的賦值運算式
>>> (lo := 7, hi := 8)
(7, 8)
>>> print(lo, hi)
7 8
uj5u.com熱心網友回復:
當我們想要使用條件運算式并想要比較兩個運算式時使用 == 運算子,如果它們為真,則執行操作,但 = 運算子用于為變數賦值。例如:
if lo == 0 and hi == len(cards) - 1:
print("Hello")
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/478407.html
