停止递归调用的函数

2024-09-27 23:15:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在返回值(x,y)(z,2)后停止下面的for循环,以便值i不会继续增加,并且在if或{}条件出现时停止

def maxPalindrome(theList):
    # students need to put some logic here
    maxcomplist = theList[:]
    maxcomplist.reverse()
    control = len(theList) - 1
    # exit if maxPalindrome is True
    for i in range(control):
        if maxcomplist[:] == theList[:]:
            x = 0
            y = len(theList)
            return (x, y)
            break
        elif maxcomplist[i:control] == theList[i:control]:
            successList = theList[i:control]
            z = i
            w = len(theList) - z - 1
            return (z, w)

我怎样才能做到这一点?在


Tags: toforlenreturnifputdefneed
2条回答

正如我在评论中所写的那样:这个函数根本不是递归函数。
递归意味着,一个函数调用它自己来完成它的目的。此调用可以是间接的,这意味着函数使用将再次调用第一个函数的helper函数。
但你的代码并不能同时涵盖这两种情况。在

递归函数总是有特定的体系结构:

  • 被调用后的第一件事应该是测试是否达到了原始大小写(或选项中的一个原始大小写)。如果是这样,它就会返回。

  • 如果没有,它将计算所需的一切并将结果再次传递给自己, 直到达到原始大小写,嵌套函数调用将一个接一个地完成。

递归的一个著名用法是quicksort算法:

def quicksort(alist):
    if len(alist) < 2: 
        return alist # primitive case: a list of size one is ordered

    pivotelement = alist.pop()
    # compute the 2 lists for the next recursive call
    left  = [element for element in alist if element < pivotelement]#left = smaller than pivotelemet
    right = [element for element in alist if element >= pivotelement]#left = greater than pivotelemet

    # call function recursively
    return quicksort(left) + [pivotelement] + quicksort(right)

所以“停止”必须是原始情况的返回。这对于递归是至关重要的。你不能随便爆发。在

我不明白这个问题-如果我做对了,你想要的已经发生了。如果return,函数将停止运行。在

除此之外,还有一些评论:

  • 同样,我看不到函数在哪里被递归调用,也看不到什么

    exit if maxPalindrome is True
    

    意味着。(这可能是一个评论吗?)

  • 此外,maxcomplist[:]==theList[:]对我来说没有太大意义,而且似乎是在浪费时间和内存,在每个迭代循环中进行这种比较并不能使它更快。

相关问题 更多 >

    热门问题