用两种不同方式从列表中搜索的功能

时间:2014-01-15 20:51:31

标签: python

我是python的新手。所以,我想知道在函数中使用哪种方法更好地在列表中查找元素。

首先:

def search_binary(xs,target):
    count = 0
    for i in xs:
        if i == target:
            return count
            count = count +1
        else:
            count = count +1
            continue
    return -1

第二

def search_binary(xs, target):
    lb = 0
    ub = len(xs)
    while True:
        if lb == ub:   
           return -1

        mid_index = (lb + ub) // 2

        item_at_mid = xs[mid_index]


        if item_at_mid == target:
            return mid_index      
        if item_at_mid < target:
            lb = mid_index + 1    
        else:
            ub = mid_index 

2 个答案:

答案 0 :(得分:1)

如果列表没有按照第一个有意义的线性搜索排序或小,但应该这样做:

# linear search O(n)
xs.index(target)

如果列表排序很大,你应该像第二个一样使用二进制搜索,但是最好使用bisect这样做:

# binary search O(log n)
from bisect import bisect_left
def search_binary(xs, target):
    i = bisect_left(xs, target)
    if i != len(xs) and xs[i] == target:
        return i
    raise ValueError

答案 1 :(得分:0)

第二,

这并非真正特定于Python,第一个是在O(n)时间运行,第二个是二进制搜索并在O(log(n))时间内运行