Recursion involves iterating over smaller instances of a complex problem to provide a solution. A recursive function repeatedly calls itself in its definition in order to produce an output. As is the case of a while loop, there needs to be a base case in order to prevent the program from running infinitely.
In class, we were introduced to recursion using the example of this function:
sum_list:
return sum([sum_list(x) if isinstance(x, list) else x for x in L])
The base case in this function is the if isinstance(x, list) stipulation. It tells the program to keep running the sum_list function on itself until it gets to an element of the nested list which is not itself a list, in which case it runs the sum method.
If the sum_list function encounters a list while traversing over the given input, it calls itself until a non-list element is encountered.
While manually tracing recursion, it's good to solve the simplest case of a problem first (a simple list of two elements, for example) and to note the results in further tracing of more complex problems (like a nested list of two levels.)
No comments:
Post a Comment