Recursion, a method used to define an object in terms of
itself. It is done this way so you can achieve a certain objective once you use
recursion for several times. For instance, we can find factorials such 5! recursively
because
n! = n x (n - 1) x (n-2) x … x 2 x 1 = (n)[(n - 1)!]
where n is an integer and n >= 1. Since programming language generally support recursion, this means functions can be used to call themselves to solve problems where recursion is involved. Most of the times, coding recursion will require precision, since the answers to the problem depends on the solution to their smaller instance calls.
n! = n x (n - 1) x (n-2) x … x 2 x 1 = (n)[(n - 1)!]
where n is an integer and n >= 1. Since programming language generally support recursion, this means functions can be used to call themselves to solve problems where recursion is involved. Most of the times, coding recursion will require precision, since the answers to the problem depends on the solution to their smaller instance calls.
If we were to code factorials by means of recursion in
python, we can return the product of the number multiply by the recursive call
using the number that is 1 less than the current number. If the current number
is 0 or 1, return 1. This means we can code it as the following:
def factorial(n) :
if n ==
0 or n == 1:
return
1
elif n
> 1:
return
n * factorial(n - 1)
It is also possible to do recursion such as factorial using
loops, but not all recursive problems can be solved without applying recursive
calls. For example, to the sum of all
the numbers in a list that contains lists of numbers and numbers. For such
recursive data structures, recursive calls can be used when the recursion depth
is either unknown or too large to code without recursion.
Often, it is possible such that our coded recursive function
may receive errors such as
RuntimeError:
maximum recursion depth exceeded
when the default
maximum recursion call limit is reached once a recursion call is
recursively called for a certain amount. The error can be fixed by either
change the default recursion call limit or create a more efficient recursive
function that requires less calls needed. If the object we performed recursion
calls on have an infinite recursion depth, recursion will not work if the Runtime
Error was not caught.
From the lectures in the recent weeks, we learnt about Tree
structures, which have a recursive data structure built in such a way that each
Tree object either links to sub Tree objects or nothing. It can be used to
represent to group data collectively in groups and subgroups.
From the past weeks, we have done countless samples regarding
recursion in class, and was test on recursion in the recent midterm. It is
import for csc students such as myself to know how to use recursion and write code of it.
No comments:
Post a Comment