最大呼叫堆栈超过了二进制搜索python

发布于 2025-01-20 19:58:40 字数 1244 浏览 0 评论 0原文

我正在尝试用Python 递归实现二分查找。

我在上面编写代码:

space = [i for i in range(4096)]

# Recursive:
def binarySearchRec(arr, low, high, target):
    if high >= low:
        mid = (high + low) // 2

        if arr[mid] == target:
            return mid
        elif arr[mid] > target:
            return binarySearchRec(arr, low, mid-1, target)
        else:
            return binarySearchRec(arr, mid, high, target)
    else:
        return -1

if __name__ == '__main__':
    element = random.choice(space)
    print(f"Index: {binarySearchRec(space, 0, len(space)-1, element)} | Number: {element}")

这应该在最多 12 个步骤中返回答案,因为复杂度为 O(log(N))。但有些运行它超出了最大调用堆栈。我怎样才能防止这种情况发生,我找不到原因。

我将非常感谢您的答复。

大家好,谢谢您的回答,

我也找到了问题的解决方案。每次目标>到达[中] 我返回的是低=中。我将其更改为 low = mid + 1。

这解决了问题,并且它的工作方式与预期的 13 个步骤中找到的最后一个元素相反。

代码:

def binarySearchRec(arr, low, high, target):
    if high >= low:
        mid = (high + low) // 2

        if arr[mid] == target:
            return mid
        elif arr[mid] > target:
            return binarySearchRec(arr, low, mid-1, target)
        else:
            return binarySearchRec(arr, mid+1, high, target)
    else:
        return -1

I am trying to implement Binary Search in Python with recursion.

I write code above:

space = [i for i in range(4096)]

# Recursive:
def binarySearchRec(arr, low, high, target):
    if high >= low:
        mid = (high + low) // 2

        if arr[mid] == target:
            return mid
        elif arr[mid] > target:
            return binarySearchRec(arr, low, mid-1, target)
        else:
            return binarySearchRec(arr, mid, high, target)
    else:
        return -1

if __name__ == '__main__':
    element = random.choice(space)
    print(f"Index: {binarySearchRec(space, 0, len(space)-1, element)} | Number: {element}")

This should return answer in max 12 steps because O(log(N)) complexity. But some runs it exceeds max call stack. How can i prevent this i can't find why.

I will be preciate for an answer.

Hey Guys thank you for answers,

I also found a solution to problem. Every time target > arr[mid]
i was returning low = mid. I changed this as low = mid + 1.

This solved the problem and it's worked as it opposed to last element found in 13 steps as it is supposed to be.

Code:

def binarySearchRec(arr, low, high, target):
    if high >= low:
        mid = (high + low) // 2

        if arr[mid] == target:
            return mid
        elif arr[mid] > target:
            return binarySearchRec(arr, low, mid-1, target)
        else:
            return binarySearchRec(arr, mid+1, high, target)
    else:
        return -1

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

内心激荡 2025-01-27 19:58:41

您的功能有效,除非可变“高”高于“低”的情况,并且目标等于高变量。这是因为高> = low是正确的,但是中间至低,这不等于目标。您可以添加:

if high - 1 == low:
    if arr[low] == target:
        return low
    return high

如果高> = low: line之前或之后。另外,您无需调用arr [x],因为arr [x] == x,所以arr [x]对x进行评估,您可以替换它。

Your function works, except in the case where variable 'high' is one above 'low', and the target is equal to the high variable. This is because high >= low is true, but mid rounds down to low, which is not equal to target. You could add:

if high - 1 == low:
    if arr[low] == target:
        return low
    return high

before or after the if high >= low: line. Also, you don't need to call arr[x], because arr[x] == x, so arr[x] evaluates to x and you can replace it.

﹉夏雨初晴づ 2025-01-27 19:58:41

在此类问题中,相差一错误很难调试。您有两个问题 -

  1. target 小于 arr[mid] 时,子问题是 low, mid
  2. target< /code> 大于 arr[mid],子问题是 mid + 1, high

我发现编写 < 有帮助> 条件和 > 条件。如果这两个条件都不满足,则 == 默认为 else 条件。

def binary_search(arr, target, low, high):
  if low >= high:
    return -1
  else:
    mid = (low + high) // 2
    if target < arr[mid]:
      return binary_search(arr, target, low, mid)       #1
    elif target > arr[mid]:
      return binary_search(arr, target, mid + 1, high)  #2
    else:
      return mid                                        # target == arr[mid]
def search(sorted_arr, q):
  return binary_search(sorted_arr, q, 0, len(sorted_arr))
foo = list(range(1000000))
print(search(foo, 523407))
523407

请注意,对于此特定问题,您不必将 range 扩展为 list。如果您实际上正在搜索范围,这可以节省大量内存。这是因为 Python 范围允许您直接使用 [] 访问元素,就像列表一样 -

bar = range(1000000)
print(search(bar, 683495)) # pass in range directly
683495

Off-by-one errors are hard to debug in problems like this one. You have two issues -

  1. When target is less than arr[mid], the sub-problem is low, mid
  2. When target is greater than arr[mid], the sub-problem is mid + 1, high

I find it helps to write the < condition and the > condition. If neither of those conditions are met, then == is by default the else condition.

def binary_search(arr, target, low, high):
  if low >= high:
    return -1
  else:
    mid = (low + high) // 2
    if target < arr[mid]:
      return binary_search(arr, target, low, mid)       #1
    elif target > arr[mid]:
      return binary_search(arr, target, mid + 1, high)  #2
    else:
      return mid                                        # target == arr[mid]
def search(sorted_arr, q):
  return binary_search(sorted_arr, q, 0, len(sorted_arr))
foo = list(range(1000000))
print(search(foo, 523407))
523407

Note for this particular problem, you do not have to expand range into a list. If you are actually searching a range, this can save a considerable amount of memory. This is because Python ranges allow you to access elements directly using [], just like lists -

bar = range(1000000)
print(search(bar, 683495)) # pass in range directly
683495
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文