Tuesday, March 4, 2014

Week 7: Recursion

Recently we learned and practiced recursion a lot. Recursion is a structure that is repeating items that has a structure that is similar to the structure of itself. For instance,
 is a recursion structure. Because all branches generated from the previous bigger branch have the same structure as the previous branches. Let me explain recursion more clearly using a simple example using Python.

def sum_list(L: list) -> float:
    """
    Return sum of the numbers in L.

    L --- a possibly nested list of numbers.  L, and all sublists, are
       non-empty

    >>> sum_list([1, 2, 3])
    6
    >>> sum_list([1, [2, 3, [4]], 5])
    15
    """
    return sum( [sum_list(x) if isinstance(x, list) else x for x in L])

What this function does is that it produces a list that contains the sum of the elements in the nested lists for every nested list in the original list and the elements in the original list if they are not lists. Then the function calculates the sum of that produced lists.

We were focusing on LinkedList this week. A LinkedList has a structure like this:
.

It contains a value in the head and a LinkedList as the rest. So it has a recursion structure. I found some methods related to LinkedList is pretty hard like __len__() because it has two base cases. One of them is when the LinkedList is empty and the second one is when self.rest is empty. This costs me lots of time in the lab.


I think the best way to enhance my knowledge with recursion is to trace the values in the function for more times and maybe draw some pictures in order to have a better understanding of the concepts.

2 comments:

  1. I like how you pointed out that recursion is not a means to itself and that it can solve other problems (trees). And I like your idea about drawing pictures to get a better understanding of recursion. I think I'm going to steal that idea from you!

    ReplyDelete