我写了一点代码试图在列表中搜索一个单词。 这不是最终版本,基本上它还不能做任何事情。 但是,我不明白代码出了什么问题:
def findword (word, t):
t.sort()
midword = t[len(t)/2]
midindex = len(t)/2
if word > midword:
del t[:midindex]
findword (word, t)
elif word < midword:
del t[midindex+1:]
findword (word, t)
elif word == midword:
return t
else:
return None
mydic=['apple','banana','peach','pear','melon','lemon','grape','berry']
mydic1 = findword('apple', mydic)
我在搜索apple
时遇到了RuntimeError: maximum recursion depth exceeded in cmp
错误,当我搜索列表中的其他单词时,它返回空列表。在
请帮我弄清楚是怎么回事。谢谢!在
如果你只是想在列表中搜索一个单词,你可以这样做--
二进制搜索的实现
首先,递归是令人讨厌的。如果可以的话,请避免这种情况——如果不走运的话,它会在非常大的搜索空间中导致这类MaxRecursion错误。在
让我们切换到迭代,看看我们能做些什么:
看看这个代码段:
在您的代码中,您会发现列表只包含两个元素,即:
^{pr2}$在这种情况下,请查看以下交互式会话:
请注意,在第19行中,您没有删除任何内容,},并进入无限递归,直到堆栈空间用完为止。你应该重新设计你的代码来克服这个问题。在
t
保持不变,然后使用相同的列表调用{我看到的另一个问题是您只是递归地调用
findword
,但没有使用返回值。而不是:您应该:
其他建议
findword
之外执行一次。在set
bisect
的库模块,它将执行二进制搜索。在相关问题 更多 >
编程相关推荐