为什么我的二分查找使用了这么多的比较?

时间:2017-08-18 05:38:34

标签: python-3.x search binary-search

这是我的代码:

def binary_search(sortedlist,target,comparisons):
start = 0
end = len(sortedlist) - 1


while(end - start >= 0):
    mid = (start + end)//2
    comparisons += 2
    if(target < sortedlist[mid]):
        comparisons -= 1
        end = mid - 1
    elif(target > sortedlist[mid]):
        start = mid + 1
    else:
        return target, comparisons
return False, comparisons

它与其他关于二进制搜索的帖子基本相同,但由于某种原因,它使用了太多的比较。

以下是我自己修复后的代码

from classes import GeneList
## Uncomment the following line to be able to make your own testing Genes
# from classes import Gene, Genome

def binary_search(sortedlist, target, comparisons):
    reducedlist = sortedlist

    while len(reducedlist) > 1:
        mid = len(reducedlist) // 2
        comparisons += 1
        if target < reducedlist[mid]:
            reducedlist = reducedlist[:mid]
        else:
            reducedlist = reducedlist[mid:]

    comparisons += 1
    if reducedlist[0] == target:
        return reducedlist[0], comparisons
    else:
        return False, comparisons


def genetic_similarity_binary(first_genome, second_genome):
    """ This function takes two Genome objects, and returns a GeneList
    and an integer. The GeneList is of all genes that are common
    between first_genome and second_genome, while the integer is
    how many comparisons it took to find all the similar genes.
    Hint: it might pay to define a helper function.
    """
    comparisons = 0
    similar_list = GeneList()
    for target in first_genome:
        result, comparisons = binary_search(second_genome, target, comparisons)
        if result:
            similar_list.append(result)
    return similar_list, comparisons

你不必做中间检查

3 个答案:

答案 0 :(得分:0)

出于优化目的,您应该首先检查终止条件。 试试这种方式,

def binary_search(sortedlist,target,comparisons):
start = 0
end = len(sortedlist) - 1


while(end - start >= 0):
    mid = (start + end)//2
    comparisons += 2
    if(target == sortedlist[mid]):
        comparisons -= 1
        return target, comparisons
    elif(target > sortedlist[mid]):
        start = mid + 1
    else:
        end = mid - 1
return False, comparisons

执行binary_search([1,2,3,4,5,6,7,8,9,10],9,0)

代码的结果为(9, 6),上述更改为(9, 5)

答案 1 :(得分:0)

你应该首先在你的程序中搜索第三个条件,然后做那个......因为第三个条件实际上是应该首先给出的终止条件......试试看。

答案 2 :(得分:0)

我自己使用远远少于比较的方法来解决它,而不是每次检查它是否相等。我不能发布我的代码,直到作业结束。