Tuesday, March 4, 2014

Recursion

Recursion is mainly used in nested lists. A nested lists is - lists within the list. We know that a list can be grouped inside another lists in a variety of ways.
To sum all the numbers in a nested list, we need to traverse the list, visiting each of the elements within the nested list, adding all those and repeating the same process for all the elements in the list which are list and then, summing up all the results within the base/main list to find the sum.
In order to decrease our efforts and coding for the long and lists with huge nested depths, Modern programming languages uses or supports Recursion - which means that function can call themselves within their definitions.

For example:


def recursive_sum(nested_num_list):
    sum = 0
    for element in nested_num_list:
        if type(element) == type([]):
            sum = sum + recursive_sum(element)
        else:
            sum = sum + element
    return sum
 The body of recursive_sum consists mainly of a for loop that traverses nested_sum_list. Here element is a numerical value, which is simply added to the sum but if an element comes out to be a list then it will  again run the same function for that elemental list. Therefore, the simple addition of the numerical values in the lists turn out to be the base case ( general implementation of the function) and the recursive call of the function turns to implement the same base case for all the elements within the sub-lists of the list.

This is the general way to deal with all the nested lists in programming in Python. i.e. first think of its base case( what the functions wants to deal with in general) and then make a recursive call to a function for all the other cases.

It surely turns out to be complicated in many cases, but with the more and more practice and by recognizing the base cases, recursion becomes the easiest way to deal with the Nested Lists with more and complicated Nested Depths.

No comments:

Post a Comment