Search code examples
pythonpython-3.xalgorithmrecursionbinary-search

RecursionError: maximum recursion depth exceeded in comparison for doing Binary Search


This is dictionary program for using python. But I found the error with like that. I want to know the reason that I saw.. If you know about that, please ask me.

Here is the error I'm getting:

$ read datafile.txt
$ size
176050
$ find Yesterday
Traceback (most recent call last):
  File "C:/Users/LG/PycharmProjects/alg1/lesson1.py", line 55, in <module>
    word_index = binarysearch(words,word,0,len(words)-1)
  File "C:/Users/LG/PycharmProjects/alg1/lesson1.py", line 25, in binarysearch
    return binarysearch(data, target,middle+1, end)
  File "C:/Users/LG/PycharmProjects/alg1/lesson1.py", line 23, in binarysearch
    return binarysearch(data,target,begin,middle-1)
  File "C:/Users/LG/PycharmProjects/alg1/lesson1.py", line 23, in binarysearch
    return binarysearch(data,target,begin,middle-1)
  File "C:/Users/LG/PycharmProjects/alg1/lesson1.py", line 23, in binarysearch
    return binarysearch(data,target,begin,middle-1)
  [Previous line repeated 994 more times]
  File "C:/Users/LG/PycharmProjects/alg1/lesson1.py", line 13, in binarysearch
    if begin > end:
RecursionError: maximum recursion depth exceeded in comparison

Process finished with exit code 1

Here is my code:

def datafile(file):
    f = open(file,'rt',encoding='UTF8')
    while True:
        line = f.readline()
        if not line:
            break
        if line == '\n':
            continue
        lines.append(line.split('\n')[0])
    return lines

def binarysearch(data,target,begin,end):
    if begin > end:
        if data[end]:  #"end" index's front data exist  
            return end
        else:
            return -1
    else:
        middle = int(begin+end/2)
        if data[middle] == target:
            return middle
        elif data[middle] > target:
            return binarysearch(data,target,begin,middle-1)
        else:
            return binarysearch(data, target,middle+1, end)


if __name__=="__main__":

    lines = []  # all list
    words = []  # list that all words is changed to lower
    pos = []  # word's pos list

    while True:
        commend = input("$ ")

        if len(commend.split()) == 2:
            second = commend.split()[1]

        first = commend.split()[0]

        if first == "size":
            print(len(lines))

        if first == "read":
            lines = datafile(second)

            for i in lines:
                words.append(i.split()[0].lower())
                pos.append(i.split()[1])

        if first == "find":
            # receive index, and print word that fitted to condition
            word = second.lower()
            word_index = binarysearch(words,word,0,len(words)-1)

            if words[word_index] in words: # if return value is middle variable
                print(lines[word_index])
                cnt = 1
                while words[word_index] == words[word_index+1]:
                    print(lines[word_index])
                    cnt = cnt + 1
                print("Found",cnt,"items.")

            else:  #if return value is the same with "end" variable                
                print("Not found")
                print(lines[word_index].split()[0],lines[word_index].split()[1])
                print("- - -")
                print(lines[word_index+1].split()[0], lines[word_index+1].split()[1])

            #print(lines[word_index])
            #print(words[word_index])

        if first == "exit":
            break

Solution

  • You have an error in your binary search algorithm:

    middle = int(begin+end/2)
    

    As division has precedence over addition, this will not calculate the middle position. It can lead to middle to become greater than end, and if data[middle] > target then the next interval will be larger in the next recursive call. This can lead to infinite recursion.

    Correct to:

    middle = int((begin+end)/2)
    

    Or simply:

    middle = (begin+end)//2