我编写了一个函数,试图找出列表中的最大值是什么:
def maxElement(L):
length=len(L)
if L[length-1]>L[length-2]:
del L[length-2]
print L
elif L[length-1]<L[length-2]:
del L[length-1]
return L
print maxElement([1,2,95754754745,3,1,8,444,2,42425])我的输出是错误的:
>>>
[1, 2, 95754754745L, 3, 1, 8, 444, 42425]
[1, 2, 95754754745L, 3, 1, 8, 444, 42425]
>>> 它甚至没有为我删除我想要的东西。我做错什么了?我搞不懂!
发布于 2016-07-22 11:24:13
您不会再次调用您的函数,这使得不可能进行递归。此外,您没有停止递归的基本情况,在本例中,这种情况是:
if length == 1:
return L这是固定代码:
def maxElement(L):
length=len(L)
if length == 1:
return L
elif L[length-1]>=L[length-2]:
del L[length-2]
elif L[length-1]<=L[length-2]:
del L[length-1]
return maxElement(L)
print maxElement([1,2,95754754745,3,1,8,444,2,42425])这一产出如下:
python recursive.py
> [95754754745L]我还在条件词上添加了<=和>=,以避免在有两个元素共享最大值的情况下进行无限递归。
发布于 2016-07-22 11:24:38
它做了你让它做的事。
您的函数不是递归的,因为您忘记了在结束时再次调用它。
像这样的东西是你要找的:
def maxElement(L):
length=len(L)
if L[length-1]>L[length-2]:
del L[length-2]
print L
elif L[length-1]<L[length-2]:
del L[length-1]
if len(L) == 1:
return L
return maxElement(L)
print maxElement([1,2,95754754745,3,1,8,444,2,42425])这将返回:
[1, 2, 95754754745L, 3, 1, 8, 444, 42425]
[1, 2, 95754754745L, 3, 1, 8, 42425]
[1, 2, 95754754745L, 3, 1, 42425]
[1, 2, 95754754745L, 3, 42425]
[1, 2, 95754754745L, 42425]
[1, 95754754745L]
[95754754745L]
[95754754745L]我会把它做得更好一点,如下:
def maxElement(L):
length=len(L)
if length == 1:
# Have this condition on the top because you are using length - 2 later
# Just return the only element
return L
if L[length-1] > L[length-2]:
# If the last element is greater than the last but one, delete the last but one
del L[length - 2]
else:
# Simple else would suffice because you are just checking for the opposite
# Also this condition saves you from:
# infinite looping when the last two elements are equal
del L[length - 1]
print L
# Time to call it recursively.
# But if you just don't want to unnecessarily increase the recursion
# tree depth, check for length and return it
if length == 1:
return L
return maxElement(L)发布于 2016-07-22 11:33:31
为什么不简单地使用max()?
最高(1,95754754745,3,8,444,2,42425) 95754754745L
https://stackoverflow.com/questions/38525085
复制相似问题