Saturday, 21 February 2015

Tracing Recursions, Slog #3

    In high school, my teacher made the class write a few easy recursive functions, for example calculating a specific value in the Fibonacci sequence. Some of these programming exercises I completed in high school gave me a half-decent foundation in recursions.

    The recursive functions we learned in class all took in a list as a parameter. In addition they all made use of the isinstance() function and a single if statement so they were pretty simple. The problem I found, was visualizing the function calls. Since we are repetitively visualizing function calls within function calls, it can get quite frustrating to keep track of each call.

     I found that tracing recursive functions becomes much easier if you know how the function works. So what I try to do when I approach a tracing problem, is first to figure out what the function does, and then do the tracing exercises. If you know what the function does, tracing it doesn’t become very difficult. 

    Obviously, the method above only works for very easy recursive functions. Some recursive functions, like quicksort  are much harder to figure out intuitively. Just look at the code we were give in class. 


def quick_sort(L):
    ''' (list) -> list

    Return a list containing the same elements as L in ascending order.

    >>> quick_sort([])
    []
    >>> quick_sort([5])
    [5]
    >>> import random
    >>> L = [1, 2, 3, 4, 5, 6, 7]
    >>> random.shuffle(L)
    >>> quick_sort(L)
    [1, 2, 3, 4, 5, 6, 7]
    '''
    if len(L) < 2: # there's nothing to sort
        return L
    else:
        return (quick_sort([x for x in L if x < L[0]]) + 
                [L[0]] + 
                quick_sort([x for x in L[1:] if x >= L[0]]))



Had there been no description of what this function does, I would be hard pressed to trace a function call. The way to get better at tracing recursions I guess, is probably the same as getting better at proofs in math. Just do more problems.

No comments:

Post a Comment