我在类定义中的二进制搜索功能有点问题:
def searchExactIndex(self, key):
bottom = 0
top = self.keyc
found = False
while bottom <= top and not found:
middle = (bottom+top)/2
if self.keys[middle] == key:
found = True
elif self.keys[middle] < key:
bottom = middle + 1
else:
top = middle-1
return middle
此处的其他所有内容都有效,除非在运行程序时出现错误:
while bottom <= top and not found:
IndentationError:意外缩进
为什么会这样?
答案 0 :(得分:1)
有了你看到的错误,
IndentationError: unexpected indent
Python试图告诉你缩进代码的方式有问题,实际上,你需要在searchExactIndex
方法的前三行之前查看缩进。
你的代码看起来很好,除了缩进,这在Python中很重要。该函数应如下所示:
def searchExactIndex(self, key):
bottom = 0
top = self.keyc
found = False
while bottom <= top and not found:
middle = (bottom+top)/2
if self.keys[middle] == key:
found = True
elif self.keys[middle] < key:
bottom = middle + 1
else:
top = middle-1
return middle
请注意设置bottom
,top
和found
的行:它们缩进为searchExactIndex
方法内部。确保使用一种类型的缩进(即只有空格),并保持一致。
答案 1 :(得分:0)
如何在python中输入此代码?
根据您的代码,您应该遇到语法错误:
如果输入文件:
File "test.py", line 4
bottom = 0
^
IndentationError: expected an indented block
如果输入交互式python:
>>> def searchExactIndex(self, key):
...
File "<stdin>", line 2
^
IndentationError: expected an indented block
解决方案是识别所有函数的内容:
def searchExactIndex(self, key):
bottom = 0
top = self.keyc
found = False
while bottom <= top and not found:
middle = (bottom+top)/2
if self.keys[middle] == key:
found = True
elif self.keys[middle] < key:
bottom = middle + 1
else:
top = middle-1
return middle
此外,当钥匙不存在时,您应该注意这种情况。现在,你总是回到中间。