Python function returns None (all trivial solution

2020-05-08 06:42发布

问题:

Now, I have written a binary search for Python (version 2.7). Sometimes, it works just fine, but at other times it returns None although the searched value is in the array. I have tried every trivial way of fixing this: I have checked whether the variable the function returns is defined, whether the branch of the workflow in which the return statement is located is executed. And: the variable is defined, the branch is executed.

Here is the code:

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)

There are a lot of 'print' statements because of my debugging. The last of them, 'print (i+1)', actually prints (!) the index value of the thing I need, but the function still returns None.

Do you have a clue about the source of the problem?

回答1:

You ignore the return value of recursive calls:

binarySearch( array, desiderata, midP + 1, iMax )

and

binarySearch( array, desiderata, iMin, midP - 1 )

So when curre < final is True:

if ( curre < final ):
    # print midP
    print "t: " + array[midP][TAPE_NUMBER] + ", d: " + desiderata
    binarySearch( array, desiderata, midP + 1, iMax )

you call binarySearch() after which your function ends. Without an explicit return that means your function return value is set to None instead.

Add return statements to those lines:

return binarySearch( array, desiderata, midP + 1, iMax )

# ...

return binarySearch( array, desiderata, iMin, midP - 1 )