What is recursion?
In math, recursion is a common concept. It means that a function is defined in terms of itself. For example, the factorial function is defined:
f(n) = n * f(n-1)
f(0) = 1
f(n) is defined in terms of function f () with a smaller number n-1. f (n - 1) is defined in terms of function f (n-2), a much smaller number n-2. The process of defining can continue until f(0) is defined as the value 0.
A recursion always has 3 parts:
- A base case
- A general case
- Finite number of calls to reach the base case from the general case.
In the case of factorial function, the base case is f(0) = 1, the general case is f(n)=n * f(n-1). After calling the f() function with smaller number for n times, it reaches the base case f(0).
In math, a function is a relationship from a set of possible inputs to a set of possible outputs where each input is related to one output. In computer science, the term function means a sequence of statements given an identifier to perform a specific task. This looks very different from the concept of function in math. But it works in similar way: a function usually takes several parameters as input and returns a value as the output, i.e. transform the input to output. A function may call other functions to perform its task. it also can call itself. The following section shows the definition of a function and the process of calling itself to reach the base case.
Python Program
# define the function factorial
# it takes one parameter n as input
# it returns the factorial of n by
# calling itself with smaller n and finally reaching the base case 0
def factorial(n):
if 0 == n: # the base case
return 1
else:
return n * factorial(n-1) # the general case
# call function factorial to calculate the factorial of 0
print(factorial(0))
# call function factorial to calculate the factorial of 5
print(factorial(5))
# call function factorial to calculate the factorial of 10
print(factorial(10))