tastyminerals
tastyminerals

Reputation: 6538

Explain recursive function for finding max element in array

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

Upvotes: 1

Views: 106

Answers (1)

Andrew Long
Andrew Long

Reputation: 1011

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.

Upvotes: 2

Related Questions