简体   繁体   English

为什么在此 Python 二进制搜索中出现“RecursionError:比较中超出最大递归深度”错误?

[英]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.

相关问题 为什么会出现RecursionError:超过最大递归深度? - Why am I getting RecursionError: maximum recursion depth exceeded? Binary Search RecursionError:比较超过最大递归深度 - Binary Search RecursionError: maximum recursion depth exceeded in comparison RecursionError:与进行二分搜索相比,超出了最大递归深度 - RecursionError: maximum recursion depth exceeded in comparison for doing Binary Search 获取 RecursionError:比较超过最大递归深度 - Getting RecursionError: maximum recursion depth exceeded in comparison RecursionError:在比较Python中超出了最大递归深度 - RecursionError: maximum recursion depth exceeded in comparison Python python编程错误RecursionError:比较超过最大递归深度 - python programming error RecursionError: maximum recursion depth exceeded in comparison 相比之下,超过了最大递归深度。 我收到此错误,但我不知道为什么在 python 中收到此错误 - maximum recursion depth exceeded in comparison. I am getting this error but I have no idea why I am getting this error in python python迷宫递归问题,RecursionError:比较中超出最大递归深度 - python maze recursion problem, RecursionError: maximum recursion depth exceeded in comparison 我不断收到此错误:RecursionError:调用Python对象时超出了最大递归深度 - I keep getting this error:RecursionError: maximum recursion depth exceeded while calling a Python object RecursionError:在比较 cs 中超出了最大递归深度 - RecursionError: maximum recursion depth exceeded in comparison cs
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM