Saturday, 1 March 2014

Recursion - Slog 7

        Recursion is the act of repeating something constantly until a conclusion is reached when it meets a specified requirement or it continues infinity. In computer science recursion is used to make a problem simpler by consistently reducing the problem to a more clean and strait forward one each time. A conclusion is reached when the smaller and smaller problem reaches a base case, a condition that exits the recursion. Without the base line, python will call the function until it runs out of memory and the program crashes. I remember the function that was taught in CSC108 - is_palindrome, this function checks if a word is a palindrome ( is the read the same forward as it is backward) I found the same example using recursion:

def is_palindrome(word):
if len(word) == 1 or len(word) == 0:
return True
else:
if word[0] == word[-1]:
            return is_palindrome(word[1:-1])
        return False

The base case is this function is the first if statement which checks if the word in of length 0 or 1 which is automatically a palindrome. Otherwise, if the character at the first index is equal to the character at the last, this is where recursion steps in to make the word smaller. If the word is ‘hello’ -> this returns False. If the word is ‘racecar’, the second statement is true and therefore the string ‘aceca’ goes through the function again. Then ‘cec’ then ‘e’ - this is where the base case is reached and the function exits and returns True. This is how recursion makes the problem simpler and simpler each time until it can be dealt with easily with the first statement. I find that this example makes it easy to understand recursion especially for me because I am very new to this concept. However there is a much easier way to write this function by simply reversing the given string and comparing the result:

def isP(s):
a = s[::-1]
    return a == s

        As the level of difficulty is increased, the use of recursion in your code will simplify seemingly difficult tasks using repetition as I found with the Tower of Hanoi from assignment 1. A recursive function makes a call to itself within the function body. When you visualize the execution of a recursive function, you will se that it repeatedly goes through the function over and over until the base case is True. After you reach the base case, you run out of lines in the function and it does an implicit return to the previous value which returns None - this makes the activation frame on the stack go away. This continues until all frames are gone. 

No comments:

Post a Comment