简体   繁体   中英

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:

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. 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM