Monday, 3 March 2014

A Revisit to Recursion

     In the beginning of the course we were introduced to an important concept of programming called recursion. Just to remind ourselves, a recursive function is one that calls itself and is used in order to solve a problem which can be broken down into smaller instances. A recursive solution is found by first solving the simplest instance (or base case) of a complex problem then using that solution to find a solution to a more complex instance, then using that solution... and you get the point by now.
     Since our introduction to recursion, we have practiced writing recursive code whether it was through finding the sum of a nested list, drawing with Python's turtles, stacking cheeses or through creating trees. These examples and practice problems during labs really helped me when it came to writing recursive code for our first test. Using the Tree class, one of the problems was to write a function two_whether which returned whether at least one value in a Tree is 2. It looked something like this:

class Tree:
    """Bare-bones Tree ADT"""

    def __init__(self: 'Tree', value: object=None, children: list=None):
        "Create a node with value and any number of children"""
        
        self.value = value
        if not children:
            self.children = []
        else:
            self.children = children[:]

def two_whether(t: Tree) -> bool
    "Return whether at least one value in tree is 2
    precondition - t is a non-empty tree with number values
    >>> tn1 = Tree(2, [Tree(4), Tree(4.5), Tree(2), Tree(5.75)]
    >>> two_whether(tn1)
    True
    """
    return t.value == 2 or any([two_whether(x) for x in t.children])

    The base case in this example was if t.value == 2, and the recursive part was searching through the children of the Tree if any of their values were == 2. 
    One of my goals in this class is still to master recursion, and after being able to answer that question on the test I feel like I am reaching closer to my goal.

No comments:

Post a Comment