现在,我已经为Python(2.7版)编写了一个二进制搜索。有时,它工作得很好,但在其他时候,尽管搜索到的值在数组中,它也不会返回任何结果。我已经尝试过每一种简单的方法来解决这个问题:我检查了函数返回的变量是否被定义,return语句所在的工作流分支是否被执行。并且:变量被定义,分支被执行。在
代码如下:
def binarySearch( array, desiderata, iMin, iMax ):
# Returns the index of the first instance of what we search
print 'min'
print iMin
print 'max'
print iMax
# If our search array is empty
if ( iMin > iMax ):
return None
midP = (iMin + iMax)/2
curre = tapeNr( array[midP][TAPE_NUMBER] )
final = tapeNr( desiderata )
print 'curre'
print curre
print 'final'
print final
print 'midP'
print midP
if ( curre < final ):
# print midP
print "t: " + array[midP][TAPE_NUMBER] + ", d: " + desiderata
binarySearch( array, desiderata, midP + 1, iMax )
else:
if ( curre > final ):
# print midP
print "t: " + array[midP][TAPE_NUMBER] + ", d: " + desiderata
binarySearch( array, desiderata, iMin, midP - 1 )
else:
print 'hooray'
# Now, find the first occurence of the value I need
i = midP
while ( array[i][TAPE_NUMBER] == desiderata ):
i -= 1
print i
print (i + 1)
return (i + 1)
由于我的调试,有很多“print”语句。 最后一个“print(i+1)”,实际上是打印(!)我需要的东西的索引值,但是函数仍然没有返回。在
你知道问题的根源吗?在
忽略递归调用的返回值:
以及
^{pr2}$所以当
curre < final
是True
:您调用
binarySearch()
,在此之后函数结束。如果没有显式返回,则意味着您的函数返回值设置为None
。在向这些行添加
return
语句:相关问题 更多 >
编程相关推荐