Python函数返回None(所有平凡解检查,他们不工作) [英] Python function returns None (all trivial solutions checked and they do not work)

查看:136
本文介绍了Python函数返回None(所有平凡解检查,他们不工作)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在,我已经写为Python(2.7版)的二进制搜索。有时,它工作得很好,但在其他时候,它虽然搜索值是数组中返回无。我试图解决这个的每一个微不足道的方式:我已经检查了函数返回变量是否已定义,是否执行其中return语句所在的工作流的分支。和:变量的的规定,分公司的是的执行。

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.

下面是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)

有很多,因为我的调试打印语句。
最后他们,打印(1 + 1)',实际打印(!)我需要的东西的索引值,但功能还是返回N​​one。

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?

推荐答案

您忽略的返回值的递归的要求:

You ignore the return value of recursive calls:

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

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

所以,当真正水流&LT;最后

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

您拨打的binarySearch()之后,你的函数结束。如果没有一个明确的回报率,这意味着你的函数的返回值设置为代替。

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

添加收益语句这些行:

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

# ...

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

这篇关于Python函数返回None(所有平凡解检查,他们不工作)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆