0

甚至问这个我都觉得很尴尬,但是python出于某种原因一直给我一个错误的“l”

    def binary_search(l, targetValue):
          low = 0, high = len(array)
          while low <= high:
                mid = (high - low)/2
                if l[mid] == targetValue:
                     return "we found it!"
                elif l[mid] > targetValue:
                     low = mid - 1;
                else        l[mid] < targetValue: #this line seems to be the problem
                     high = mid + 1;
          print "search failure :( "
4

2 回答 2

6

虽然你的间距不正常,但实际上不是这里的问题。

问题是由您使用else表达式引起的。相反,您需要使用elif

elif l[mid] < targetValue:

或者,更好的是,完全摆脱表达式,因为您已经测试了l[mid] == targetValueand l[mid] > targetValue

else:

else意思是“为了其他任何事情,做这个”。因此,它不评估也不支持表达式。

于 2013-11-14T21:58:18.377 回答
2

Your last line "#this line seems to be the problem" should be an ELIF or an ELSE with no statement afterwards. For example, you do not need "ELSE {Condition}". ELSE means "everything else."

于 2013-11-14T22:00:02.740 回答