Python递归函数不返回

Python递归函数不返回,python,recursion,Python,Recursion,我正在尝试编写一个递归函数,返回一个单词在已排序单词列表中的位置,或者在找不到该单词时返回None。代码如下: def partition(t,kw,upper,lower): if ((upper-lower) > 1): pivot = lower + (upper-lower)//2 print("pivot is now {}".format(pivot)) if (kw >= t[pivot]):

我正在尝试编写一个递归函数,返回一个单词在已排序单词列表中的位置,或者在找不到该单词时返回
None
。代码如下:

def partition(t,kw,upper,lower):
    if ((upper-lower) > 1):
        pivot = lower + (upper-lower)//2
        print("pivot is now {}".format(pivot))
        if (kw >= t[pivot]):
            lower = pivot
            print("searching on the right",upper,lower)
            return(partition(t,kw,upper,lower))
        
        elif (kw <= t[pivot-1]):
            upper = pivot-1
            print("searching on the left",upper,lower)
            return(partition(t,kw,upper,lower))

        else:
            return None 
            #that means the keyword is between t[pivot-1] and t[pivot]
            #which means it doesnt exist in the list
    if (upper - lower) <= 1:
        if (kw == t[upper]):
            print("found element {} at upper bound {}".format(kw,upper))
            return(upper)
        elif (kw == t[lower]):
            print("found element {} at lower bound {}".format(kw,lower))
            return(lower)
        else:
            return None

def search(t, kw):
    u = len(t)
    partition(t,kw,u,0)
我在搜索单词
“Qing”
,它应该位于第31位。 现在,函数似乎可以找到我需要的单词,但无法返回:

the result is
pivot is now 92
searching on the left 91 0
pivot is now 45
searching on the left 44 0
pivot is now 22
searching on the right 44 22
pivot is now 33
searching on the left 32 22
pivot is now 27
searching on the right 32 27
pivot is now 29
searching on the right 32 29
pivot is now 30
searching on the right 32 30
pivot is now 31
searching on the right 32 31
found element Qing at lower bound 31
None

我试图搜索与递归函数相关的问题,但似乎没有太多相关的内容。SO上的大多数帖子都是由于没有返回递归函数引起的,我真的不确定这里出了什么问题。

您的函数似乎正常工作。我想你只是忘了从搜索中返回,即

def search(t, kw):
    u = len(t)
    lower = partition(t,kw,u,0)
    return lower
输出

...
searching on the right 32 30
pivot is now 31
searching on the right 32 31
found element Qing at lower bound 31
31
正如伟大的回答所指出的,您忽略了在
搜索
函数中添加
return
语句。但是,代码中有一些地方可以改进:

def partition(t, kw, upper, lower):
    if upper - lower > 1:
        pivot = lower + (upper - lower) // 2
        print("pivot is now {}".format(pivot))
        if kw >= t[pivot]:
            lower = pivot
            print("searching on the right", upper, lower)
            return partition(t, kw, upper, lower) 
        if kw <= t[pivot - 1]:
            upper = pivot - 1
            print("searching on the left", upper, lower)
            return partition(t, kw, upper, lower)
    if upper - lower <= 1:
        if kw == t[upper]:
            print("found element {} at upper bound {}".format(kw, upper))
            return upper 
        if kw == t[lower]:
            print("found element {} at lower bound {}".format(kw, lower))
            return lower

def search(t, kw):
    u = len(t)
    return partition(t, kw, u, 0)

lst = ['', '', '150', '150', '1997,with', '36', '49', 'An', 'Annotated', 'Annotation', 'Bibliography', 'China', 'Chinese', 'Chinese', 'Classical', 'During', 'Dynasty', 'Hong', 'Hong', 'Hong', 'Hong', 'Hong', 'In', 'It', 'Kong', 'Kong', 'Kong', 'Kong,', 'Kong.', 'Mainland', 'Poets', 'Qing', 'They', 'Together,', 'Writings', 'a', 'a', 'a', 'a', 'a', 'active', 'activity,', 'addition', 'almost', 'and', 'and', 'and', 'and', 'and', 'and', 'annotations', 'anthologies', 'basic', 'been', 'before.', 'bibliographic', 'bibliographies,', 'by', 'carry', 'ci-poetry', 'ci-poetry', 'classical', 'collected', 'commentaries', 'compilation,', 'compilations', 'compiled', 'covered,', 'development', 'events', 'focused', 'form', 'form', 'formation,', 'from', 'from', 'has', 'help', 'hidden', 'in', 'in', 'in', 'in', 'includes', 'individual', 'information', 'information', 'introduces', 'invaluable', 'is', 'late', 'literary', 'literati', 'literature', 'literature.', 'membership,', 'most', 'never', 'not', 'of', 'of', 'of', 'of', 'of', 'of', 'of', 'of', 'of', 'of', 'offer', 'on', 'on', 'on', 'on', 'order', 'over', 'past', 'periods', 'pioneer', 'pity', 'poetic', 'poetry', 'poetry', 'poetry', 'poet’s', 'political', 'previous', 'previously', 'published', 'refuge', 'research', 'sequel', 'shi-', 'shi-', 'societies', 'societies', 'societies', 'societies.', 'societies.', 'splendor,', 'that', 'that', 'the', 'the', 'the', 'the', 'the', 'the', 'the', 'the', 'the', 'the', 'the', 'the', 'these', 'these', 'these', 'this', 'times', 'to', 'to', 'to', 'to', 'to', 'to', 'took', 'tools', 'topic', 'tradition.', 'turmoil', 'two', 'uncover', 'understand', 'understanding', 'unique', 'up', 'various', 'very', 'volume,', 'which', 'works,', 'worthwhile', 'would', 'years,']
print(search(lst, "Qing"))
实际上,每秒
if
语句也可以被删除(如中,删除
if
行并取消其内容),但为了可读性,保留它们是可以的


另外,如果您使用的是Python3,
“Example number{}”.format(5)
元素可以替换为
f“Example number{5}”

单一用途、简化的

正如所写的那样,分区是一个很大的函数,有许多参数试图做很多事情。是否有可能将它的一些关注点分离开来,使它更具可用性?我们是否可以抽象掉一些复杂性,使函数更容易编写,更不容易出错

为了研究改进分区的方法,我们将首先研究Python的
范围
数据结构。在您的实现中,您使用了以下算法来获得解决方案-

  • 上部-下部>1
  • lower+(上-下)//2
  • kwb:r=r[p+1:]
    如果a==b:中断
    
    def搜索(t,kw):
    尝试:
    r=范围(0,长度(t))
    p=分区(r)
    v=无
    尽管如此:
    i=p.send(v)
    如果kw==t[i]:返回i
    v=(千瓦,t[i])
    除停止迭代外:
    一无所获
    
    请提供完整的–其中包括代码的实际调用方式。您只是想从
    def search
    返回
    31
    ?如果是这样,您需要添加一个
    return
    语句!
    def partition(t, kw, upper, lower):
        if upper - lower > 1:
            pivot = lower + (upper - lower) // 2
            print("pivot is now {}".format(pivot))
            if kw >= t[pivot]:
                lower = pivot
                print("searching on the right", upper, lower)
                return partition(t, kw, upper, lower) 
            if kw <= t[pivot - 1]:
                upper = pivot - 1
                print("searching on the left", upper, lower)
                return partition(t, kw, upper, lower)
        if upper - lower <= 1:
            if kw == t[upper]:
                print("found element {} at upper bound {}".format(kw, upper))
                return upper 
            if kw == t[lower]:
                print("found element {} at lower bound {}".format(kw, lower))
                return lower
    
    def search(t, kw):
        u = len(t)
        return partition(t, kw, u, 0)
    
    lst = ['', '', '150', '150', '1997,with', '36', '49', 'An', 'Annotated', 'Annotation', 'Bibliography', 'China', 'Chinese', 'Chinese', 'Classical', 'During', 'Dynasty', 'Hong', 'Hong', 'Hong', 'Hong', 'Hong', 'In', 'It', 'Kong', 'Kong', 'Kong', 'Kong,', 'Kong.', 'Mainland', 'Poets', 'Qing', 'They', 'Together,', 'Writings', 'a', 'a', 'a', 'a', 'a', 'active', 'activity,', 'addition', 'almost', 'and', 'and', 'and', 'and', 'and', 'and', 'annotations', 'anthologies', 'basic', 'been', 'before.', 'bibliographic', 'bibliographies,', 'by', 'carry', 'ci-poetry', 'ci-poetry', 'classical', 'collected', 'commentaries', 'compilation,', 'compilations', 'compiled', 'covered,', 'development', 'events', 'focused', 'form', 'form', 'formation,', 'from', 'from', 'has', 'help', 'hidden', 'in', 'in', 'in', 'in', 'includes', 'individual', 'information', 'information', 'introduces', 'invaluable', 'is', 'late', 'literary', 'literati', 'literature', 'literature.', 'membership,', 'most', 'never', 'not', 'of', 'of', 'of', 'of', 'of', 'of', 'of', 'of', 'of', 'of', 'offer', 'on', 'on', 'on', 'on', 'order', 'over', 'past', 'periods', 'pioneer', 'pity', 'poetic', 'poetry', 'poetry', 'poetry', 'poet’s', 'political', 'previous', 'previously', 'published', 'refuge', 'research', 'sequel', 'shi-', 'shi-', 'societies', 'societies', 'societies', 'societies.', 'societies.', 'splendor,', 'that', 'that', 'the', 'the', 'the', 'the', 'the', 'the', 'the', 'the', 'the', 'the', 'the', 'the', 'these', 'these', 'these', 'this', 'times', 'to', 'to', 'to', 'to', 'to', 'to', 'took', 'tools', 'topic', 'tradition.', 'turmoil', 'two', 'uncover', 'understand', 'understanding', 'unique', 'up', 'various', 'very', 'volume,', 'which', 'works,', 'worthwhile', 'would', 'years,']
    print(search(lst, "Qing"))
    
    pivot is now 92
    searching on the left 91 0
    pivot is now 45
    searching on the left 44 0
    pivot is now 22
    searching on the right 44 22
    pivot is now 33
    searching on the left 32 22
    pivot is now 27
    searching on the right 32 27
    pivot is now 29
    searching on the right 32 29
    pivot is now 30
    searching on the right 32 30
    pivot is now 31
    searching on the right 32 31
    found element Qing at lower bound 31
    31