[英]Why am i getting “RecursionError: maximum recursion depth exceeded in comparison” error on this Python Binary Search?
I wrote this Binary Search as a task for my Uni:我写了这个二分搜索作为我的 Uni 的一项任务:
def bin_search(l,i,start,end):
if start >= end:
return False
else:
pos = (start + end) // 2
if i == l[pos]:
return True
elif i < l[pos]:
return bin_search(l,i,start,pos)
else:
return bin_search(l,i,pos,end)
I keep getting a RecursionError: maximum recursion depth exceeded in comparison
error message.我不断收到
RecursionError: maximum recursion depth exceeded in comparison
错误消息。 If i change the last line to:如果我将最后一行更改为:
return bin_search(l,i,pos + 1,end)
it does not happen, I do not understand why this is because as I understood it in the not working code the same range of the list plus one more should be given as a parameter.它没有发生,我不明白为什么会这样,因为正如我在不工作的代码中所理解的那样,列表的相同范围加上一个应该作为参数给出。 Can you please tell me where my mistake is.
你能告诉我我的错误在哪里吗?
Try this:尝试这个:
def bin_search(l,i,start = 0,end):
if start >= end:
return False
else:
pos = (start + end) // 2
if i == l[pos]:
return True
elif i < l[pos]:
return bin_search(l,i,start + 1,pos)
else:
return bin_search(l,i,pos + 1,end)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.