最大呼叫堆栈超过了二进制搜索python
我正在尝试用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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的功能有效,除非可变“高”高于“低”的情况,并且目标等于高变量。这是因为高> = low是正确的,但是中间至低,这不等于目标。您可以添加:
如果高> = 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:
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.在此类问题中,相差一错误很难调试。您有两个问题 -
target
小于arr[mid]
时,子问题是low, mid
target< /code> 大于
arr[mid]
,子问题是mid + 1, high
我发现编写
<
有帮助> 条件和>
条件。如果这两个条件都不满足,则==
默认为else
条件。请注意,对于此特定问题,您不必将
range
扩展为list
。如果您实际上正在搜索范围
,这可以节省大量内存。这是因为 Python 范围允许您直接使用[]
访问元素,就像列表一样 -Off-by-one errors are hard to debug in problems like this one. You have two issues -
target
is less thanarr[mid]
, the sub-problem islow, mid
target
is greater thanarr[mid]
, the sub-problem ismid + 1, high
I find it helps to write the
<
condition and the>
condition. If neither of those conditions are met, then==
is by default theelse
condition.Note for this particular problem, you do not have to expand
range
into alist
. If you are actually searching arange
, this can save a considerable amount of memory. This is because Python ranges allow you to access elements directly using[]
, just like lists -