【问题标题】:Validation in recursive Python function is met, but after that execution continues on else statemen满足递归 Python 函数中的验证,但之后继续执行 else 语句
【发布时间】:2021-12-06 17:17:12
【问题描述】:

我很困惑为什么在满足并执行条件后,该函数不返回 -1 而是继续执行 else 语句。

如果 len(arr) == 1 和 arr[mid] != n: 返回 -1

给定数组 = [2, 3, 4, 10, 40] 并且如果:

  • x = 1 -> -1(正常)
  • x = 5 -> 1(索引,错误)
  • x = 50 -> 3(索引,错误)
  • 如果 x 在列表中,则函数返回正确的索引

当我运行调试器时,最终,数组减少到 1 个元素,但 if 语句没有按我预期的那样工作。 我的错在哪里,谢谢?

def binary_search(arr, n):

# if n not in arr:
#     return -1


  mid = len(arr) // 2

  if len(arr) == 1 and arr[mid] != n:
      return -1

  elif n == arr[mid]:
      return mid  

  elif n < arr[mid]:
      return binary_search(arr[:mid], n)

  else:
      return mid + binary_search(arr[mid:], n)

【问题讨论】:

    标签: python recursion


    【解决方案1】:

    您的 else 语句将中点索引添加到 binary_search 的返回值。因此,一旦到达最后一个元素,就在堆栈中返回 -1,然后将该返回值添加到前一个堆栈的中点,即 1。然后返回 -1 + 1,即 0,因此返回0 到中点为 2 的最后一个堆栈,因此返回 2 + 0 即 2。

    def binary_search(arr, n):
        # if n not in arr:
        #     return -1
    
        mid = len(arr) // 2
    
        if len(arr) == 1 and arr[mid] != n:
            return -1
    
        elif n == arr[mid]:
            return mid
    
        elif n < arr[mid]:
            return binary_search(arr[:mid], n)
    
        else:
            return binary_search(arr[mid:], n)
    
    print(binary_search( [2, 3, 4, 10, 40], 11))
    
    -1
    

    【讨论】:

    • 如果我理解正确,每次(在我的代码中)执行 else 语句时,中间值被放入堆栈,一旦我到达基本情况,堆栈中所有值的总和 - 1 被退回。对吗?
    【解决方案2】:

    Chris Doyle回答后,我按如下方式更改了功能,现在似乎可以正常工作了:

    def binary_search(arr, n, idx=0):
    
      mid = len(arr) // 2
    
      if len(arr) == 1 and arr[mid] != n:
          return -1
    
      elif n == arr[mid]:
          return idx + mid
    
      elif n < arr[mid]:
          return binary_search(arr[:mid], n, idx)
    
      else:
          return binary_search(arr[mid:], n, idx + mid)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-03
      • 1970-01-01
      • 2021-05-13
      • 1970-01-01
      • 1970-01-01
      • 2021-08-10
      相关资源
      最近更新 更多