我正在学习用 Python 编写算法。并且出现了无效的语法错误,代码附在下面,在第 9、2、18 行发誓
def binary_search(list, item):
low = 0
high = len(list)-1
while low <= high:
mid = (low + high)
guess = list[mid]
if guess == item:
return mid
if guess > item:
high = mid - 1
else:
low = mid + 1
return None
my_list = [1, 3, 5, 7, 9]
print binary_search(my_list, 3)
print binary_search(my_list, -1)
最有可能对未知变量低和项目发誓。可以通过将行从 while 移动到 return(不包括 return)向右移动到上一行 high = ... 的水平来解决这个问题。像这样:
Python 对缩进很敏感,因为它认为 binary_search 函数已经结束,因此无法理解这些变量是什么——它们不在主程序中,它们只在函数中。
如果你有 Python 3,那么你需要在 print 上加上括号: