[英]Python Sorting and Binary Search IndexError: list index out of range
我正在努力了解此代碼中的錯誤:
def arr_sort_binsearch(ar):
ar.sort()
first = 0
last = len(ar)-1
found = False
item = 8
for num in ar:
while first<=last and not found:
midpoint = (first + last)//2
if ar[midpoint] + num == item:
found = True
else:
if item < ar[midpoint]:
last = midpoint-1
else:
first = midpoint+1
print("{} and {} is: {}".format(num, ar[num], item))
ar = [1,3,5,7]
arr_sort_binsearch(ar)
我收到一個異常消息,說我的索引超出范圍。 我了解什么是索引溢出的理論,只是我無法在代碼中找到它。
錯誤是我認為這句話:
print("{} and {} is: {}".format(num, ar[num], item))
num不應是ar中的參數
干杯
如果您嘗試編寫二進制搜索,則您的代碼不正確。
1,回答您的問題,為什么IndexError: list index out of range
:
用於循環遍歷輸入列表ar
的代碼為num
,最后print
,該元素將為ar[num]
的索引,這會引發錯誤,例如:
您有ar=[1,2,3,4,5,8,9,11,6]
,當循環到9
, print
嘗試使用ar[9]
,但是列表ar
只有9個元素,超過最大索引8
,這將引發IndexError: list index out of range
。
2,您的二進制搜索可以這樣修改:
def arr_sort_binsearch(ar,item):
ar.sort()
first = 0
last = len(ar)-1
found = False
while first<=last and not found:
midpoint = (first + last)//2
if ar[midpoint] == item:
found = True
else:
if item < ar[midpoint]:
last = midpoint-1
else:
first = midpoint+1
return found
如果調用函數,這將返回True或False:
arr_sort_binsearch([1,2,3,4,5,8,9,11,6],12)
返回False
arr_sort_binsearch([1,2,3,4,5,8,9,11,6],8)
返回True
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.