二进制搜索算法的Python代码无法编译

时间:2017-01-06 00:13:52

标签: python algorithm

我试图在Python中实现二进制搜索算法。 我在手机上写了这段代码,但它没有编译。 而且我不知道它为什么不编译。 (我还没有在电脑上试过它。)

def BinarySearch(sList, search):
    res=0
    sortedList=sorted(sList)
    x=int(len(sortedList)/2)
    mid=sortedList[x]
    def DivideSearch(sortedList ,search ):
        first=sortedList[:mid ]
        second=sortedList[mid:]
        if first[len(first)-1]<search:
            DivideSearch (first, search)
        elif second[len(second)-1]>search:
            DivideSearch (second, search)
        elif len(first)==1:
            res=first.pop()
        elif len(second)==1:
            res=second.pop()
    if res==search:
        return res


numbers=[1,2,3,4,5,6,7,8,9]
guess=3

print(BinarySearch(numbers,guess ))

是什么阻止了这段代码的编译? 我的错误是什么?如何解决?

2 个答案:

答案 0 :(得分:0)

def binarys(list, item):

   #you have to keep track of the head(lo) of the list and tail(hi)

   lo = 0

   #a list must be sorted for binary search to work because the lower values are on the left and higher on the right

   slist = sorted(list)
   hi = len(slist) - 1

  #Keep running the search as long as the start of the list is never less than or equal to the end of the list. At that point you either have 1 item left to check or the item isn't there at all. So return False

   while lo <= hi:
      mid = (lo + hi)//2

      #if the item you searched for is in the middle, return True
      if slist[mid] == item:
         return True

      #since it's not in the middle the first time you checked, but if the item you're looking for is less than the value of the mid item in the list then you can ignore the entire right part of the list by making the item to the left of the midpoint the new tail(hi). midpoint minus 1 because you already established the midpoint of the original list didn't have the item you searched for.
      elif item < slist[mid]:
         hi = mid - 1

      # if the item you're looking for is greater than the value of the mid item in the list then you can ignore the entire left part of the list by making the item to the right of the midpoint the new head(lo). midpoint plus 1 because you already established the midpoint of the original list didn't have the item you searched for.
      else:
         if item > slist[mid]:
            lo = mid+ 1
   return False

print(binarys([1,2,3,4,5,6,7,8,9,10], 1))

答案 1 :(得分:0)

首先,您的代码在我的计算机上正常运行。其次,你的逻辑是有缺陷的。永远不会在res函数中分配BinarySearch(),因为它与父函数的范围不同。此外,您的基本情况检查不应在firstsecond上完成,应在功能开头的sortedList处完成。此外,您可以检查是否在DivideSearch()函数中找到了值。我正在上传更正后的代码,看看这个

import random
def DivideSearch(sortedList, search, mid):
    first = sortedList[:mid]
    second = sortedList[mid:]
    #check for our base case
    if len(sortedList) ==1:
        return sortedList[0] if sortedList[0] == search else None
    #we can immediately remove half the cases if they're less than or greater than our search value
    #if the greatest value element in the lower half is < search value, only search the higher value list
    if first[-1] < search:
        #recurse
        return DivideSearch(second, search, len(second)/2)

    #otherwise we want to check the lower value list
    else:
        return DivideSearch(first, search, len(first)/2)

def BinarySearch(sList, search):

    sortedList=sorted(sList)
    #determine mid cleanup
    mid=len(sortedList)/2
    #return the result
    return DivideSearch(sortedList,search, mid)



numbers=[random.randint(1, 10) for x in range(1,10)]
guess=5