我在类定义中的二进制搜索功能有一个小问题:
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: unexpected indent
为什么是这样?
最佳答案
看到错误,
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
方法内部。确保使用一种缩进类型(即仅空格),并保持一致。
关于python - 二进制搜索和外部函数 'return'错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21281212/