Saturday, 1 March 2014

Recursion(Recursion(Recursion)))

Recursive code... where to begin...?

Think of recursive code as one big circle - in order for a function to run it calls on itself.

Take this example that I found
source: http://www.loyalty.org/~schoen/python/class-4-recursion.txt 

def factorial(n):
 if n == 0:
  return 1
 else;
  return n*factorial(n-1)

The function factorial(n) takes a number n, and then calls on itself with in its body.
The body also requires a base case, in this case if n == 0, which stops the recursive circle. If not the circle will continue until eventually the computer runs out of memory space - which leads to a very ugly output in the python shell. Other wise, it runs through the code until the (n-1) conditions leads to n being equal to 0, in which case it returns 1.

No comments:

Post a Comment