I find recursion to be really fascinating. There are three principles for a recursive function:
1. There must be a base case.
2. The function algorithm must tend towards that base case.
3. The function must call itself.
An example of a recursive function is a function that calculates factorials.
def factorial(n):
if n == 1:
return n
else:
return n * factorial(n-1)
>>> print(factorial(5))
120
As one can observe in this function, the base case is when n is equal to 1, in which case it will return n, or else it will move towards that base case by multiplying n when it's not 1 with the factorial of n-1.
Recursion looks like it is a staple of computer science and problem solving in general.
No comments:
Post a Comment