def ternary_search(seq,key):
length=len(seq)
left=0
right=length
index=0
x=True
while x and left<=right:
if left==right:
return index
#once you know left==right,check and see if the value==key and if so then return either the left or right as both must be the index of that value
else:
if right-left>0:
index1 = ((right+2*(left))//3)
index2 = ((2*(right)+left)//3)
if left == right:
x = False
return (index1+index2)
if seq[index1] == key:
x = False
return index1
if seq[index2]== key:
x = False
return index2
if key<seq[index1]:
right = index1-1
else:
if key > seq[index1] and key <seq[index2]:
right = index2-1
left = index1-1
if key > seq[index2]:
left = index2+1
return index
def test():
seq = []
for i in range(1,1001):
seq.append(i)
for j in range(1,1001):
is_pass = (ternary_search(seq,j)==j-1)
assert is_pass == True, "fail the test when key is %d"%j
if is_pass == True:
print("=========== Congratulations! Your have finished exercise 2! ============")
if __name__ == '__main__':
test()
I have this program, and I know where the error is occurring, and I left an idea of what I think should be done to fix it, but its still not working can someone please help me.

New Topic/Question
Reply



MultiQuote




|