【问题标题】:binary search implementation with python用python实现二分查找
【发布时间】:2013-08-02 07:01:10
【问题描述】:

我认为我做的一切都是正确的,但是如果值不存在,基本情况返回 None,而不是 False。我不明白为什么。

def binary_search(lst, value):
    if len(lst) == 1:
        return lst[0] == value

    mid = len(lst)/2
    if lst[mid] < value:
        binary_search(lst[:mid], value)
    elif lst[mid] > value:
        binary_search(lst[mid+1:], value)
    else:
        return True

print binary_search([1,2,4,5], 15)

【问题讨论】:

  • 你可以使用 bisect 模块,但也许这是家庭作业?

标签: python algorithm python-2.x


【解决方案1】:

需要返回递归方法调用的结果:

def binary_search(lst, value):
    #base case here
    if len(lst) == 1:
        return lst[0] == value

    mid = len(lst)/2
    if lst[mid] < value:
        return binary_search(lst[:mid], value)
    elif lst[mid] > value:
        return binary_search(lst[mid+1:], value)
    else:
        return True

我认为您的 ifelif 条件是相反的。那应该是:

if lst[mid] > value:    # Should be `>` instead of `<`
    # If value at `mid` is greater than `value`, 
    # then you should search before `mid`.
    return binary_search(lst[:mid], value)
elif lst[mid] < value:  
    return binary_search(lst[mid+1:], value)

【讨论】:

【解决方案2】:

因为如果什么都不返回!

if lst[mid] < value:
    binary_search(lst[:mid], value)
    # hidden return None
elif lst[mid] > value:
    binary_search(lst[mid+1:], value)
    # hidden return None
else:
    return True

【讨论】:

    【解决方案3】:

    您还需要从ifelifreturn

    def binary_search(lst, value):
        #base case here
        if len(lst) == 1:
            return lst[0] == value
    
        mid = len(lst) / 2
        if lst[mid] < value:
            return binary_search(lst[:mid], value)
        elif lst[mid] > value:
            return binary_search(lst[mid+1:], value)
        else:
            return True
    

    >>> print binary_search([1,2,4,5], 15)
    False
    

    【讨论】:

      【解决方案4】:

      二分查找:

      def Binary_search(num,desired_value,left,right):
          while left <= right:
              mid = (left + right)//2
              if desired_value == num[mid]:
                  return mid
              elif desired_value > num[mid]:
                  left = mid + 1
              else:
                  right = mid - 1
          return -1
      num =[12,15,19,20,22,29,38,41,44,90,106,397,399,635]
      desired_value = 41
      result = Binary_search(num,desired_value,0,len(num)-1)
      if result != -1:
          print("Number found at " + str(result),'th index')
      else:
          print("number not found")
      

      【讨论】:

        【解决方案5】:
        def rBinarySearch(list,element):
            if len(list) == 1:
                return element == list[0]
            mid = len(list)/2
            if list[mid] > element:
                return rBinarySearch( list[ : mid] , element )
            if list[mid] < element:
                return rBinarySearch( list[mid : ] , element)
            return True
        

        【讨论】:

          【解决方案6】:
          def binary_search(lists,x):
              lists.sort()
              mid = (len(lists) - 1)//2
              if len(lists)>=1:
                  if x == lists[mid]:
                      return True
          
                  elif x < lists[mid]:
                      lists = lists[0:mid]
                      return binary_search(lists,x)
          
                  else:
                      lists = lists[mid+1:]
                      return binary_search(lists,x)
              else:
                  return False
          a = list(map(int,input('enter list :').strip().split()))
          x = int(input('enter number for binary search : '))
          (binary_search(a,x))
          

          【讨论】:

          • 这如何帮助理解问题中代码的执行如何返回None?此处提供的代码缺少代码 cmets。 binary_search(sequence, key) 迫切需要一个 doc string预计会在 O(log(len(sequence))) 时间内运行,但 lists.sort() 使它成为 o(len(sequence))。
          【解决方案7】:
          def binary_search(arr, elm):
              low, high = 0, len(arr) - 1
          
              while low <= high:
                  mid = (high + low) // 2
                  val = arr[mid]
              
                  if val == elm:
                      return mid
                  elif val <= elm:
                      low = mid + 1
                  else:
                      high = mid - 1
                  
              return -1
          
          
          print(binary_search([2, 3, 4, 6, 12, 19, 20, 21], 12)) # 4
          print(binary_search([2, 3, 4, 6, 12, 19, 20, 21], 3333)) # -1
          

          【讨论】:

            【解决方案8】:
            def Binary_search(li, e, f, l):
                mid = int((f+l)/2)
                if li[mid] == e:
                    print("Found",li[mid] )
                elif f == l-1 and li[mid] != e:
                    print("Not Found ")
                elif e < li[mid]:
                    Binary_search(li, e, f,mid)
                elif e > li[mid]:
                    Binary_search(li, e, mid,l)
            
            
            
            elements = [1,2,4,6,8,9,20,30,40,50,60,80,90,100,120,130,666]
            Binary_search(elements, 120, 0, len(elements))
            

            【讨论】:

            • 这如何帮助理解问题中代码的执行如何返回NoneBinary_search() 是否返回任何有用的信息?有Style Guide for Python Code
            • 请解释旅游代码以及它如何解决问题中的问题。
            猜你喜欢
            • 1970-01-01
            • 2018-04-13
            • 1970-01-01
            • 2023-03-05
            • 2014-05-10
            • 2016-02-23
            • 1970-01-01
            • 2010-10-28
            • 1970-01-01
            相关资源
            最近更新 更多