【发布时间】:2013-03-12 02:26:01
【问题描述】:
下面有一个名为“test”的函数。我的程序无法通过测试功能。
这是我的三元搜索代码。三元搜索类似于二分搜索,但不是将所有元素除以二,而是将它们除以三。
为了使用三元搜索,我使用 index2 作为 1/3 项目的分隔符。 index1 是 2/3 项的分隔符。
您只需将“高”和“低”分配给 index1 或 index2。这使您可以将列表分为三个部分。 High 和 Low 用于查找您应该搜索的划分列表的哪一部分。然后这个过程不断重复,直到high和low的值接近。
seq 是列表中的项目,即。 [1,2,3,4,5...] 列表中的项目是有序的。
key 是我正在寻找的值
并且ternary_search返回键的索引或接近键的数字的索引
玩得开心! 干杯!
def ternary_search(seq,key):
length = len(seq)
left = 0
right = length
index = 0
x = True
while x and left <= right:
#focal = (high + low) //3
if left == right:
#check similarity between values and key
return index
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()
【问题讨论】:
-
如果列表中有两个项目,它可以工作,但如果有三个或更多,我会出错
-
显示输入示例,以及您得到的错误。
-
def test() 如果你运行这个程序,它会自动给你输入和错误。它在页面的底部
-
这是一个相当老的问题,但是阅读答案后,我看到很多人声称三元搜索很可能比二分搜索慢,而且确实如此直观。事实证明,事实并非如此。因为数组的长度是 2 的幂是非常常见的,并且由于 CPU 将地址映射到缓存行的方式,二进制搜索算法实际上是 CPU 缓存的病态案例,正如这篇很棒的博客文章所解释的那样:@987654321 @
标签: python python-3.x binary-search ternary-search