二进制搜索功能

时间:2012-10-31 22:04:04

标签: python algorithm search binary binary-search

晚上好。我正在尝试重新编程并决定在我自己的时间进行一些练习编码。我目前正在尝试实现二进制搜索,但在我的代码中似乎存在连续循环。有人能给我一些关于发生了什么的暗示吗?

def binChop(key, ordered_set):

    found = False
    newSet = ordered_set

    while found != True or newSet > 0:
        midpoint = int(len(newSet)/2)
        if key < newSet[midpoint]:
            found = False
            newSet = newSet[:midpoint]
        elif key > newSet[midpoint]:
            found = False
            newSet = newSet[midpoint:]
        elif key==newSet[midpoint]:
            found = True
    return found

3 个答案:

答案 0 :(得分:1)

我认为你的问题是在while循环的条件下。你有'或'而不是'和' - 这意味着即使你找到你的结果,也会满足newSet&gt; 0条件。

答案 1 :(得分:1)

我怀疑“newSet&gt; 0”始终为真。如果它是一个标准的python集,你会收到一个错误:

>>> b=set()
>>> b
set([])
>>> b > 0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only compare to a set

但是既然你没有,我想这是一个列表或元组:

>>> a=[]
>>> a > 0
True
>>> b=()
>>> b > 0
True

两者都没有达到预期效果(检查长度)。

通常,将import pdb; pdb.set_trace()添加到代码中并逐步执行以查找错误。

答案 2 :(得分:1)

您有一些问题,有些问题可以改进:

  • 当元素不在有序列表中时,您需要左右边界索引才能正确执行二进制搜索。查看正确的算法here。当您找到密钥或左边界位于右边界右侧时,您会离开while循环,反之亦然(max_point < min_point)。
  • 您不需要newSet。您始终可以在排序列表中使用索引。所以mid_point只是一个索引,所以min_point(左边界)和max_point(右边界)。
  • 二进制搜索通常返回key的索引作为return。如果找不到,请返回-1

我的python代码如下所示:

def binChop(key, ordered_list):

    min_point, max_point = 0, len(ordered_list)-1

    while min_point <= max_point:
        mid_point = (min_point+max_point)/2

        if ordered_list[mid_point] < key:
            min_point += 1
        elif ordered_list[mid_point] > key:
            max_point -= 1
        else:
            return mid_point
    return -1

test_cases = [[], [5], [4,5], [5,6], [1,5,6], [1], [1,4], [1,6,15]]
for ordered_list in test_cases:
    print "%-10s %5s" % (ordered_list, binChop(5, ordered_list))

Outputs:
list       index of 5
[]            -1
[5]            0
[4, 5]         1
[5, 6]         0
[1, 5, 6]      1
[1]           -1
[1, 4]        -1
[1, 6, 15]    -1      
相关问题