Wednesday, March 2, 2016

Week 7 SLOG

Hello everyone,
    I would like to talk more about recursion in this SLOG. Thinking more about the quiz on recursion from last week, I tried to recall what I wrote on the quiz and run it through python to see if it would work, and if what I wrote on the quiz is what I think I wrote on the quiz, then I found that it works! This is what I believe I wrote:

def count_characters(string_list):
    """Returns the total number of characters in a list.

    @type string_list: list | str
    @rtype: int
    """
    if isinstance(string_list, list):
        n = 0
        for i in string_list:
            n += count_characters(i)
        return n
    else:
        return len(string_list)

Well, I hope that is what I wrote...

    Anyways, I did some research on recursion and what I found got me quite interested in recursion. In point form, I found that:
-Problems that can be solved with recursion can usually be solved with loops.
-Loops can sometimes be a more efficient that recursion.
-Recursive functions take up more memory and resources than a loop.
These may all seem like reasons to not use recursion, but what is interesting is that recursion is also usually faster and easier to code than a loop, and you can get the same results as a loop. While reading about recursion, I also found a good way to think about recursive functions. They usually follow two rules:

1. If the problem can be solved simply without recursion, return a value
2. If the problem cannot be solved simply without recursion, reduce the size of the problem and call the recursive function inside the smaller problem.

If we look at the code I wrote earlier, that is exactly what I had done. If string_list is a list, I reduce the problem and call recursion until to solve the problem I don't need recursion. If string_list is not a list, I return a value, len(string_list). It is quite simple actually!

-Anthony Arena

1 comment:

  1. Wow, so talented. You have a gift sir. Would partner with, 10/10.

    ReplyDelete