Monday, 9 February 2015

Recursion

Today I'm going to talk about recursion and recursion tracing. Sorry for this post being late, I've been pretty stressful lately. But you probably aren't here to read about that. And if you are, that
wouldn't really make much sense. Anyways, on to recursion.
I've often recursion described as when a function is defined by itself. A basic example could be:

def count_total(lst):
    if not isinstance(lst, list):
        return lst
    else:
        return sum([count_total(i) for i in lst])

This function adds all the elements in a list, including elements in nested lists.  A comment on my last post asked how I would explain recursion, considering that its solving a problem using the problem. Pretty complicated stuff. The way I see it, it's like you're expanding a problem, or going deeper. In the example above, you call the function count_total on each element in a list, then call it on each list element in the list, and so forth until you get to the non-list elements. From what I've seen of recursion so far, there is always eventually a situation where you stop calling the original function - here, it's when an element is not a list. I haven't seen much recursion, but I'd imagine that you need that to happen unless you want the function to keep calling itself forever, like an infinite loop.

Recursion tracing really shows the expansion aspect - it reminds me of expanding polynomials in math. If we try the above example on the list [1, 3, [6, [1]], 4], we get:
    --> sum([count_total(i) for i in lst]
    --> sum([count_total(1), count_total(3), count_total([6, [1]]), count_total(4),])
    --> sum([1, 3, count_total(6), count_total([1]), 4])
    --> sum([1, 3, 6, count_total(1), 4])
    --> sum([1, 3, 6, 1, 4])
    --> 15

Recursion tracing seems to me like the kind of thing which seems easy at first, but can quickly get complicated and confusing. It is helpful when trying to understand why recursion code I'm writing doesn't work, but it's also a bit tedious at times.

Thanks for reading! Or if you just skimmed/skipped most of this and went to the end, well that's okay too. Everyone's busy, it's understandable.
  


No comments:

Post a Comment