二进制搜索字符串

时间:2015-12-17 05:28:20

标签: python binary-search

我对python(3.3)相对较新,我只是试图通过一个单词列表进行二进制搜索,并且无法弄清楚如何在循环索引时修复我的操作数类型。 ..我继续得到TypeError。无法解决任何问题

def find(L, target):
    start = 0
    end = len(L) - 1

    while start <= end: 
        middle = (start + end)// 2 
        midpoint = L[middle]
        if midpoint > target:
            end = midpoint - 1
        elif midpoint < target:
            start = midpoint + 1
        else:
            return midpoint

我正在调用函数:

L = [“Brian”,“Meg”,“Peter”,“Joe”,“Stewie”,“Lois”]

找到(L,“乔”)

3 个答案:

答案 0 :(得分:3)

你的逻辑似乎很好,除了输入以及增加和减少中点而不是中间的错误。

def find(L, target):
    start = 0
    end = len(L) - 1

    while start <= end:
        middle = (start + end)/ 2
        midpoint = L[middle]
        if midpoint > target:
            end = middle - 1
        elif midpoint < target:
            start = middle + 1
        else:
            return midpoint

L = ["Brian", "Joe", "Lois", "Meg", "Peter", "Stewie"] # Needs to be sorted.

print find(L, "Peter")

答案 1 :(得分:1)

def find(L, target):
    start = 0
    end = len(L) - 1
    while start <= end:
        middle = (start + end)// 2
        midpoint = L[middle]
        if midpoint > target:
            end = middle - 1
        elif midpoint < target:
            start = middle + 1
        else:
            return midpoint

    L = ["Brian", "Joe", "Lois", "Meg", "Peter", "Stewie"]
    L = sorted(L)
    print(find(L, "Lois"))

正如其他人所指出的,使用中间而不是中点

为了最佳地使用二进制搜索,请先对列表进行排序

答案 2 :(得分:0)

def binarySearchOnString(arr, x):
        l = 0
        r = len(arr) - 1
        while (l <= r): 
            m = (l + r) // 2 
            if (arr[m] == x): 
                return m
            elif (arr[m] < x): 
                l = m + 1
            else: 
                r = m - 1
        return -1  #   If element is not found  then it will return -1