【问题标题】:RecursionError: maximum recursion depth exceeded in comparison for doing Binary SearchRecursionError:与进行二分搜索相比,超出了最大递归深度
【发布时间】:2019-03-17 15:27:58
【问题描述】:

这是使用python的字典程序。但是我发现了这样的错误。我想知道我看到的原因.. 如果你知道这件事,请问我。

这是我得到的错误:

$ 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

这是我的代码:

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

【问题讨论】:

  • 您还没有向我们展示datafile.txt 包含的内容。没有它有点难以调试......列表大小为 176050,你的函数应该递归的最大次数应该是log_2(176050) = 18。因此,您的二进制搜索功能可能存在错误。但是我在这里做了很多假设。请查看How to Ask 并创建一个minimal reproducible example

标签: python python-3.x algorithm recursion binary-search


【解决方案1】:

你的二分搜索算法有错误:

middle = int(begin+end/2)

由于除法优先于加法,因此不会计算中间位置。它可能导致middle 变得大于end,如果data[middle] &gt; target 则在下一次递归调用中下一个间隔将更大。这会导致无限递归。

更正:

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

或者简单地说:

middle = (begin+end)//2

【讨论】:

  • 谢谢你回答我的问题:) 谢谢你,我解决了这个问题。实际上我是使用这个堆栈溢出网站的初学者,所以我认为我的问题看起来有点难..我会尝试习惯使用这个网站的选项!再次感谢您的努力:)。祝你有美好的一天
  • 不客气! ;-) 请您勾选答案旁边的灰色标记,以便将其标记为已接受?
猜你喜欢
  • 2022-08-23
  • 2020-10-10
  • 1970-01-01
  • 2019-04-18
  • 2021-02-13
  • 2017-03-24
  • 2016-09-19
  • 2019-03-23
  • 2020-10-08
相关资源
最近更新 更多