二进制搜索未在列表中查找值

时间:2015-03-17 19:27:56

标签: python binary-search

不确定我的代码是怎么回事。我有一个通用的二进制搜索功能来返回列表中的位置。它的工作时间有一半。

我有一个包含内容的列表:

['drag_part_num', 'sku', 'name', 'manufacturer', 'price', 'color', 'diameter', 'finish', 'made in the u.s.a.', 'material', 'model', 'position', 'specific application', 'style', 'type', 'width', 'att_fitment', 'thumbnail', 'small_image', 'image', 'media_gallery', 'type', 'simple_skus']

这是我的二元搜索:

def binary_search(self, a, x, lo=0, hi=None):   # can't use a to specify default for hi
    hi = hi if hi is not None else len(a) # hi defaults to len(a)   
    pos = bisect_left(a,x,lo,hi)          # find insertion position
    return (pos if pos != hi and a[pos] == x else -1) # don't walk off the end

当我运行print self.binary_search(headerList, 'color')时 它返回-1。我不明白这是怎么可能的。

思考?

1 个答案:

答案 0 :(得分:1)

要使二进制搜索起作用,需要对列表进行排序:

from bisect import bisect_left

def binary_search(a, x, lo=0, hi=None):   # can't use a to specify default for hi
    hi = hi if hi is not None else len(a) # hi defaults to len(a)
    pos = bisect_left(a,x,lo,hi)          # find insertion position
    return (pos if pos != hi and a[pos] == x else -1) # don't walk off the end

header_list = sorted(['drag_part_num', 'sku', 'name', 'manufacturer', 'price',
                      'color', 'diameter', 'finish', 'made in the u.s.a.',
                      'material', 'model', 'position', 'specific application',
                      'style', 'type', 'width', 'att_fitment', 'thumbnail',
                      'small_image', 'image', 'media_gallery', 'type',
                      'simple_skus'])

print(header_list)
print(binary_search(header_list, 'color'))

输出:

['att_fitment', 'color', 'diameter', 'drag_part_num', 'finish', 'image',
 'made in the u.s.a.', 'manufacturer', 'material', 'media_gallery', 'model',
 'name', 'position', 'price', 'simple_skus', 'sku', 'small_image',
 'specific application', 'style', 'thumbnail', 'type', 'type', 'width']
1