我正在嘗試使用遞回實作對整數串列的二分搜索,并通過每次對串列進行切片來“消除”一半的專案。我寫了一些,如果達到目標值,我應該回傳“True”的部分被卡住了。我會反復檢查“左”是否大于“右”,但我想讓函式的引數盡可能簡單。
def binary_search(iterable, target):
left_index = 0
right_index = len(iterable)
mid = (left_index right_index) // 2
if iterable[mid] == target:
return True
elif iterable[mid] < target:
iterable = iterable[mid:right_index]
print(iterable)
binary_search(iterable,target)
elif iterable[mid] > target:
iterable = iterable[left_index:mid]
print(iterable)
binary_search(iterable,target)
uj5u.com熱心網友回復:
False如果未找到該值,則回傳以下內容;否則回傳索引。二分查找遞回執行。
代碼的關鍵添加是return呼叫函式。我添加了一些return a b if a != False else a邏輯,False如果值不在可迭代中,則處理回傳。
def binary_search(iterable, target):
# if the list is down to one element, and it isn't the target, return False
if len(iterable) == 1 and iterable[0] != target: return False
left_index = 0
right_index = len(iterable)
mid = (left_index right_index) // 2
if iterable[mid] == target:
return mid
elif iterable[mid] < target:
iterable = iterable[mid:right_index]
v = binary_search(iterable,target)
# if v is not False, add it to the left side of the window and return
# else return False
return v mid if v != False else v
elif iterable[mid] > target:
iterable = iterable[left_index:mid]
v = binary_search(iterable,target)
return v left_index if v != False else v
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/337436.html
上一篇:如何實作自然數的集合論定義>
