Saturday, 1 March 2014

Recursion

Week 7 already. We are almost done with this course! We had the test last week as all of you know. How did you find it? Any thing challenging? The question about trees was a bit hard for me to answer as I am still struggling with that. But it was a fair test. Labs the week of the test, I didn't mind. The lab itself was hard. No one in my lab could do the Queue with linked lists which was annoying because I spent 2 hours stuck!

Recursion! Where to start. Let's start with the basics. Recursion is when you define a function, and in its code, it calls on itself. It always has a base case, which is the simplest case that it can call on and usually it will return something here or do something i.e. add to a list. Then when we have more complicated calls on the function i.e. nested listed, or lists with a length larger then n, and this is when the recursion happens. An example is a nested list, the base case would be when we have having a list where none of the elements are lists, and then the more complex cases, where we would use recursion, would involve at least one element in the list being a list. We can have multiple elements that are lists, we can have an element in the list that is a list that contains a list, ie, a nested list.

Here is a sample of code:

def code(x: list) :
      '''Returns the max number in a list.
    
    >>> code([5, 21, 10])
    21
    >>> code([5, [11, [27, 6]], 10])
    27
    """
    return max([code(x) if isinstance(x, list) else x for x in L])
    
This code is an example of what I explained above. What it does is it looks at every element in the list and if it is not a list, it will simply add it to a new list, this is the base case. If the element is a list, then it will call on itself, and read through every element in this list. In short it will keep on going deeper and deeper into a nested list, recursion, until it finds a non-list element , base case.

No comments:

Post a Comment