这是我的代码。
def trin_search(A,first,last,target):
#returns index of target in A, if present
#returns -1 if target is not present in A
if first>last:
return -1
else:
one_third=first+(last-first/3)
two_thirds=first+2*(last-first)/3
if A[one_third]==target:
return one_third
elif A[one_third]>target:
#search the left-hand third
return trin_search(A,first, one_third-1],target)
elif A[two_thirds]==target:
return two_thirds
elif A[two_thirds]>target:
#search the middle third
return trin_search(A,one_third+1,two_thirds-1,target)
else:
#search the right-hand third
return trin_search(A,two_thirds+1,last,target)
这是一个三元递归搜索。我不断收到此错误:
line 24, in trin_search
if A[one_third]==target:IndexError: list index out of range
但我无法想象为什么。这是我在 shell 中运行程序的方式:
>>>> A=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
>>>> trin_search(A,A[0],A[len(A)-1],5)
任何帮助深表感谢。