In order to understand the advanced algorithm concepts like greedy methods and dynamic programming, one first need to be well versed in recursion.
I am relatively new to
Let's take a simple task. Printing numbers from 1 to 10. I'll use Python2.7 here.
for i in range(1,11):
print i
Now let's try to do the same, using recursion.
>>> def print_me(n):
if n > 0:
print_me(n - 1)
print n
else:
return
>>> print_me(10)
1
2
3
4
5
6
7
8
9
10
So how do we think of it ?
Step3: We start by writing a function that does the job of printing a number passed as an argument. Let's think of just, the main task.
def print_me(n): print n
Step 4: I want the function to return, if n < 1.
def print_me(n): if n > 0: print n else: return
Step 5: Now I want to pass numbers, from 1 to 10 to this function, but we don't want a loop of 1 to 10 , and then pass it to our function. We want it to be done recursively.
What is recursion? In plain words, the repeated application of a recursive procedure or definition.
So in order to make it recursive, we need to call the function itself. And we want to pass our range of 1 to 10.
def print_me(n):
if n > 0:
print_me(n - 1)
print n
else:
return
Summarizing: All recursive calls must obey 3 important rules:
Source : interactivepython
Another program in Javascript to find factorial:
function factorial(n){
if (n == 1)
{
return 1;
}
else {
return n * factorial(n-1);
}
}