Find Maximum Number in a Nested List Recursively

Lab2.1 Find Maximum in a Nested List Recursively


You are expected write a recursive python function to find the largest number within a given list. The list may contain numbers and strings and, you are expected to ignore the strings. In addition, the list may be a nested list with several nesting levels and you are expected to consider the numbers in all the nesting levels.

A = [2, 4, 6, 8, [[11, 585, "tu"], 100, [9, 7]], 5, 3, "ccc", 1]

def M(L):

    # If list is empty, return nothing
    if len(L) == 0:
        return
    
    # If the list size is one, it could be one element or a list
    if len(L) == 1:

        # If it's a list, get the maximum out of it
        if isinstance(L[0], list):
            return M(L[0])
        # If it's a string, ignore it
        if isinstance(L[0], str):
            return
        # Else return the value
        else:
            return L[0]
        
    # If the list has more elements, find the maximum
    else:
        return max(M(L[:1]), M(L[1:]))


print A
print M(A)

Comments

Popular posts from this blog

Mocking Point Clouds in ROS Rviz

Python Laboratory Excersices