代码之家  ›  专栏  ›  技术社区  ›  yrrah2

为什么我的二进制搜索使用这么多比较?

  •  0
  • yrrah2  · 技术社区  · 7 年前

    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 回复  |  直到 7 年前
        1
  •  0
  •   Bhavya Saggi    7 年前

    出于优化目的,您应该首先检查终止条件。

    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)

        2
  •  0
  •   Chandan Suri    7 年前

    您应该首先在程序中搜索第三个条件,并在该条件中执行必要的操作。。。因为第三个条件实际上是终止条件,应该首先给出。。。试试看。

        3
  •  0
  •   yrrah2    7 年前

    我自己解决了这个问题,通过不检查每次是否相等,使用了少得多的比较。直到作业结束,我才能发布代码。