Sunday, 2 March 2014

Recursion

A recursive method is very simply defined as a method that calls itself.  It can be called as assigned to a variable within the function, or as a part of the return statement.
 
Recursive methods are designed to sift through every nested layer of data, gather all the elements, and collect or return the information you're looking for.
For example:  if you wanted to return a list (in any nested structure) with 2 added to every number listed anywhere, you could write a return statement like:
def add2(lst: list) -> None:
... (shortened just for explanation)   
      return ([add2(x) if isinstance(x, list) else x + 2 for x in lst])
 
A sample input of:
a = [1, 2, [3], [4, [5, 6]]]
 
Would return:
[3, 4, [5], [6, [7, 8]]]
when add2(a) is called in the shell.
 
This is a very basic example to show how the recursive function access each element of the inputted parameter.

These functions can return a single quantity as compared to other elements in a nested list, can add up or multiply all the elements in the nested list, can extract/modify/delete any or all elements in the various levels of recursion in the given parameter so that the end result is achieved by only calling the function once.

No comments:

Post a Comment