Sunday, 23 February 2014

Recursion

Recursion is a method of problem solving that is based around the idea of taking a complex problem, breaking it down into more easily solves instances of itself, and then finalizing it into a complete solution. Simply put, recursion is a function that calls itself. For example, here is a piece of code that can be used to calculate the factorial of any given number:

def factorial(n):
    fact = 1
    for i in range(1, n + 1):
        fact = fact * i
    return fact

The Factorial of n is calculated by multiplying all the numbers between 1 and n. The above code gives an iterative solution. In order to come up with the recursive solution for the problem, we must first understand that the nth Factorial number is n * Fact(n - 1). Alternatively said, if you know the Factorial for one number, you can calculate the Factorial for the next number. This would be the recursive solution for the factorial number of n:

def recursive_factorial(n):
    if n < 2:
        return 1
    return n * recursive_factorial(n - 1)

In this solution, I placed a threshold to stop the code from iterating through itself forever. This is what is known as the Base Case. In this case, the program returns the number 1 whenever the function is called with an argument value of 1 or less. The program also has something called the Recursive Step, where we call the same method with a slightly modified parameter.

During the first assignment, there were many problems that took me longer than expected to deal with. However, by using the my computer science's "Piazza" website, I was able to conquer many of the problems I came face to face with. The problems I could not solve using this website, I simply went onto Stack Overflow which gave me a greater insight onto how similar problems to the problem I was currently working on were solved. It was also very beneficial asking my friends in the class, as well as my lab partner to give me help on specific parts of the assignment. In all, without communication with my classmates through the Piazza website, and during class hours, I would have had a much more difficult with the assignment. I am very grateful for this, and hope that I can repay their efforts by continuing to be actively social with others taking the CSC148 course.

No comments:

Post a Comment