我试图在返回值(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)
我怎样才能做到这一点?在
正如我在评论中所写的那样:这个函数根本不是递归函数。
递归意味着,一个函数调用它自己来完成它的目的。此调用可以是间接的,这意味着函数使用将再次调用第一个函数的helper函数。
但你的代码并不能同时涵盖这两种情况。在
递归函数总是有特定的体系结构:
被调用后的第一件事应该是测试是否达到了原始大小写(或选项中的一个原始大小写)。如果是这样,它就会返回。
如果没有,它将计算所需的一切并将结果再次传递给自己, 直到达到原始大小写,嵌套函数调用将一个接一个地完成。
递归的一个著名用法是quicksort算法:
所以“停止”必须是原始情况的返回。这对于递归是至关重要的。你不能随便爆发。在
我不明白这个问题-如果我做对了,你想要的已经发生了。如果
return
,函数将停止运行。在除此之外,还有一些评论:
同样,我看不到函数在哪里被递归调用,也看不到什么
意味着。(这可能是一个评论吗?)
此外,
maxcomplist[:]==theList[:]
对我来说没有太大意义,而且似乎是在浪费时间和内存,在每个迭代循环中进行这种比较并不能使它更快。相关问题 更多 >
编程相关推荐