Recursion
Recursion
Recursion...................................................................................................................................................1
Python Recursive Function......................................................................................................................1
Example of a recursive function..............................................................................................................2
Advantages of Recursion.........................................................................................................................4
Disadvantages of Recursion...................................................................................................................5
Recursion
Recursion is the process of defining something in terms of itself.
if x == 1:
return 1
else:
return (x * factorial(x-1))
num = 3
print("The factorial of", num, "is", factorial(num))
Output
The factorial of 3 is 6
In the above example, factorial() is a recursive function as it calls
itself.
Output
Traceback (most recent call last):
File "<string>", line 3, in <module>
File "<string>", line 2, in a
File "<string>", line 2, in a
File "<string>", line 2, in a
[Previous line repeated 996 more times]
RecursionError: maximum recursion depth exceeded
Advantages of Recursion
Recursive functions make the code look clean and elegant.
A complex task can be broken down into simpler sub-problems
using recursion.
Sequence generation is easier with recursion than using some
nested iteration.
Disadvantages of Recursion
Sometimes the logic behind recursion is hard to follow through.
Recursive calls are expensive (inefficient) as they take up a lot
of memory and time.
Recursive functions are hard to debug.