Lucia Lucia - 4 months ago 8
Python Question

Finding the maximum element with a recursive function

I wrote a function that tries to find out what has the maximum value in a list:

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])


My output is wrong:

>>>
[1, 2, 95754754745L, 3, 1, 8, 444, 42425]
[1, 2, 95754754745L, 3, 1, 8, 444, 42425]
>>>


It doesn't even delete for me what I've ask for. What did I do wrong? I can't get it!

Answer

You are not calling your function again, which makes recursion impossible. Furthermore you have no base case which would stop recursion, which in this case would be:

if length == 1:
  return L

Here is the fixed code:

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])

This outputs:

python recursive.py
 > [95754754745L]

I also added <= and >= on the conditionals to avoid infinite recursion if there are two elements that share the maximum value.

Comments