Python Ca2
Python Ca2
Output:
Factorial of number 6 = 720
BASE CONDITION:
In the recursive program, the solution to the base case is provided
and the solution to the bigger problem is expressed in terms of
smaller problems.
def fact(n):
if n <= 1:
return 1
else:
return n*fact(n-1)
In the above example, the base case for n < = 1 is defined and the
larger value of a number can be solved by converting to a smaller one
till the base case is reached.
Output:
The factorial of 5 is: 120
INDIRECT RECURSIVE FUNCTION:
In Indirect recursive functions, two functions mutually call each other
wherein both the functions must have a base case. Let's understand
using a flowchart.
Output:
5 is even: False
5 is odd: True
TAIL RECURSION:
Tail recursion is a specific form of recursion where the recursive call is
the last operation performed by the function. In other words, the
result of the recursive call is immediately returned without any
further computation. This type of recursion is particularly interesting
because it can be optimized by some programming languages
(though not by Python due to its lack of proper tail call optimization).
Here's an example of a tail-recursive function to calculate the
factorial of a non-negative integer:
def factorial(n, accumulator=1):
if n == 0:
return accumulator
else:
return factorial(n - 1, accumulator * n)
result = factorial(5)
print("Factorial of 5 is:", result)
Output: Factorial of 5 is: 120
CONCLUSION
Recursion in Python is a powerful technique where a function calls
itself directly or indirectly, allowing elegant solutions to complex
problems. It enables breaking down problems into simpler
subproblems and solving them iteratively, often following a divide-
and-conquer approach. Python supports both direct and indirect
recursion, offering flexibility in problem-solving. While recursion
promotes code readability and modularity, it may lead to stack
overflow errors if not implemented with proper base conditions.
Though Python lacks tail call optimization, recursion remains valuable
for its simplicity and versatility in algorithmic design and problem-
solving. Overall, mastering recursion in Python enhances a
programmer's ability to tackle a wide range of computational
challenges efficiently and elegantly.
REFERENCES
Jenny Bryan, Jim Hester, and STAT545 Teaching Assistants. Happy git and
GitHub for the user. https://happygitwithr.com/, 2021. URL:
https://happygitwithr.com/.
Hadley Wickham and Jenny Bryan. R Packages. O'Reilly Media, Inc., 2015.