1

I decided to incorporate recursions into my code and for that I want to train using it. I have a recursive function which finds the max element in the given array.

def maxx(lst):
    if len(lst) == 1:
        return lst[0]
    else:
        m = maxx(lst[1:])
        return m if m > lst[0] else lst[0]

maxx([1,3,2])
> 3

I tried to draw a sequence of events and I can't get why the code above works? Because according to what I see it should be 2 not 3. Where is my mistake? Is there a method that correctly expands the recursion and thus helps you to understand its flow?

enter image description here

1
  • Check in your notes the content of the array in each recursion. When you get back the 2 from the last return, you compare it with array[0], which is 3 so you return 3, then you go up again and array[0] is 1 so 3 goes out again. P.S. It's confusing to read that you expect the code to throw out a 2 looking for max value :) Commented May 11, 2017 at 19:12

1 Answer 1

2

Depth 0:

lst = [1,3,2]
m = maxx([3,2])

Depth 1:

lst = [3,2]
m = maxx([2])

Depth 2:

lst = [2]
returning 2

Back to Depth 1:

lst = [3,2]
m = 2
return m (2) if m > lst[0] (3) else return lst[0] (3)
returning 3

Back to Depth 0:

lst = [1,3,2]
m = 3
return m (3) if m > lst[0] (1) else return lst[0] (1)
returning 3

The reply by Alfabravo is correct, I think that's where you lost track of lst[0] as you went back up the tree.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.