【发布时间】:2016-12-01 20:30:27
【问题描述】:
所以我写了一个二分搜索算法,但是当我测试运行时它不能完美运行。
这里是代码
def binarySearch(lst, target):
low = 0
high = len(lst)-1
while high >= low:
mid = (high + low)//2
if target < lst[mid]:
high = mid - 1
elif target > lst[mid]:
low = mid + 1
else:
return mid
return (-1 * (mid+1))
这里是调用函数的代码
lst_test = [3, 4, 6, 7]
target_values = [1, 3, 5, 8]
for t in target_values:
i = binarySearch(lst_test, t)
if (i < 0):
print("In", lst_test, t, "is going to be inserted at index",-1*(i+1))
lst_test.insert((i+1)*-1, t)
else:
print("In", lst_test, t, "was found at index", i)
print("The final list is:", lst_test)
问题是这样的,当我实际运行它提供的函数时,我想将列表 target_values 添加到第一个正确的顺序中
In [3, 4, 6, 7] 1 is going to be inserted at index 0
In [1, 3, 4, 6, 7] 3 was found at index 1
In [1, 3, 4, 6, 7] 5 is going to be inserted at index 3
In [1, 3, 4, 5, 6, 7] 8 is going to be inserted at index 5
The final list is: [1, 3, 4, 5, 6, 8, 7]
这很奇怪,它工作但它只在通话的最后部分失败 有没有办法解决这个问题?最终列表应该是 [1,3,4,5,6,7,8]
根据要求,我跟踪了我的二进制搜索算法,它的质量很差。我希望这会有所帮助
Mid point is: 1
target value is smaller than a mid point
Mid point is: 0
target value is smaller than a mid point
In [3, 4, 6, 7] 1 is going to be inserted at index 0
Mid point is: 2
target value is smaller than a mid point
Mid point is: 0
target value is larger than a mid point
Mid point is: 1
Found the index location at 1
In [1, 3, 4, 6, 7] 3 was found at index 1
Mid point is: 2
target value is larger than a mid point
Mid point is: 3
target value is smaller than a mid point
In [1, 3, 4, 6, 7] 5 is going to be inserted at index 3
Mid point is: 2
target value is larger than a mid point
Mid point is: 4
target value is larger than a mid point
Mid point is: 5
target value is larger than a mid point
In [1, 3, 4, 5, 6, 7] 8 is going to be inserted at index 5
The final list is: [1, 3, 4, 5, 6, 8, 7]
【问题讨论】:
-
你在跟踪调用顺序方面做得很好;你能把它应用到二分搜索例程中吗?以您表现出的谨慎程度,我敢打赌,那里有 2 或 3 个打印语句会向您显示错误。
-
旁注:你知道the
bisectmodule,对吧?如果这是一个学习练习,请玩得开心,但除此之外,请使用随附的电池;它们比您可能自己实现的任何东西都更快、更灵活。
标签: python algorithm binary-search