Friday, 21 February 2014

Recursion

Recursion, simply stated, is the use of something within itself. At face value, this definition can make recursion seem either simple, or daunting; however, in either case, recursion proves very powerful. At one point in a recursive function, the function will call itself to reach a certain goal. Functions using concepts such as for loops can be rewritten as recursive functions. The following example will demonstrate this.

def repeater(a: str, b: int):
    """ Return a string containing string a repeated integer b times
    
    >>> repeater('hey', 3)
    'heyheyhey'
    >>> repreater('S', 5)
    'SSSSS'
    """
    new_string = ""
    
    for i in range(b):
        new_string += a
        
    return new_string

How This Works: a is accumulated b times in a new string through iterations of a for loop. 

def repeater_recursive(a: str, b: int):
    """ Return a string containing string a printed integer b times
    
    >>> repeater_recursive('hey', 3)
    'heyheyhey'
    >>> repeater_recursive('S', 5)
    'SSSSS'
    """
    if b == 0:
        return ""
    else:
        return a + repeater_recursive(a, b - 1)

How This Works: Consider the if statement. If parameter b is 0, a is to repeat 0 times in a new string, which is why an empty string is returned. Otherwise, continue to the else statement. This is where the recursive fun begins. "return a" gets us started with the first accumulation of a in the new string. To accumulate according to b, repeater_recursive() calls itself. The second parameter of repeater_recursive() in the body of the else statement is 1 less than it was at first. This is because we already have a single a accumulated from "return a". Once it calls itself, it will again go through the if-else statement, and apply itself accordingly. The second parameter in the repeater_recursive() call in the else statement will be 0 once no more a's need to accumulate into the returning string. This will at last return an empty string, as previously mentioned, and the function will end.

During this week I'll be focused on beginning Stage 1 of A2 while studying for the midterm. I think it's good to see a Stage 1 of A2 due at a time prior to the next. I typically wait too late to begin an assignment, as I did with A1, and this causes me to fail in many aspects. This time around I'm determined to overcome this issue of mine. So stay tuned, CSC148 TAs, for you haven't heard the last of me.


No comments:

Post a Comment