Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Could someone explain why this function doesn't always return the first element of the list

I have been having a look at some simple recursive functions to wrap my head around the concept. However one example has me a little confused.

The function below uses recursion to obtain the largest integer from a list:

A = [-4, 2, 4]
n = len(A)
def findMaxRec(A, n):
    if (n == 1):
        return A[0]
    else:
        return max(A[n - 1], findMaxRec(A, n - 1))

As n will eventually equal 1 why does the function not always return the first element in the list?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

In such cases it might be helpful to just write out what code will be executed. I’ve tried to do that with your function as pseudo-code, where n is replaced with its value:

findMaxRec(A, 3):
    if (3 == 1):
        return A[0]
    else:
        return max(A[3 - 1], 
            findMaxRec(A, 2):
                if (2 == 1):
                    return A[0]
                else:
                    return max(A[2 - 1], 
                        findMaxRec(A, 1):
                            if (1 == 1):
                                return A[0]
                )
    )

Effectively, this results in:

max(A[2], max(A[1], A[0]))

Where the inner call max(A[1], A[0]) = max(2, -4) = 2

And the outer call max(A[2], ...) = max(4, 2) = 4

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading