Reverse a Nested List Recursively

Lab2.2 Reverse a Nested List Recursively


You are expected to write a python program to reverse a list which may have nested lists within it. The number of nesting levels is not limited.

As an example, the reversed list of
[1, 2, [31, 32], 4, [51, [521, 522], 53], 6] will be
[6, [53, [522, 521], 51], 4, [32, 31], 2, 1]

A = [1, 2, [31, 32], 4, [51, [521, [12, 25, [4, 78, 45], 456, [444, 111]],522], 53], 6]

def reverseList(L):

    # Empty list
    if len(L) == 0:
        return

    # List with one element
    if len(L) == 1:
        
        # Check if that's a list
        if isinstance(L[0], list):
            return [reverseList(L[0])]
        else:
            return L
        
    # List has more elements
    else:
        # Get the reversed version of first list as well as the first element
        return reverseList(L[1:]) + reverseList(L[:1])


print A
print reverseList(A)

Comments

Post a Comment

Popular posts from this blog

Python Laboratory Excersices

Mocking Point Clouds in ROS Rviz

Find Maximum Number in a Nested List Recursively