Code:
def fibonacci_tail_recursive(n, a=0, b=1):
if n == 0:
return a
elif n == 1:
return b
else:
return fibonacci_tail_recursive(n - 1, b, a + b)
print(fibonacci_tail_recursive(7))
Solution and Explanation:
Let's break down the code step by step:
def fibonacci_tail_recursive(n, a=0, b=1):
This line defines a function called fibonacci_tail_recursive that takes three parameters: n, a, and b. n represents the term of the Fibonacci sequence to compute, while a and b represent the current and next terms of the sequence respectively. By default, a is set to 0 and b is set to 1.
if n == 0:
return a
elif n == 1:
return b
Here, the function checks if the input n is 0 or 1. If n is 0, it returns the current term a (which is 0). If n is 1, it returns the next term b (which is 1). These base cases terminate the recursion.
else:
return fibonacci_tail_recursive(n - 1, b, a + b)
If n is greater than 1, the function makes a recursive call to itself with the parameters (n - 1, b, a + b). This means it calculates the next term by adding the current term a to the next term b, and it decrements n by 1 to move closer to the base cases. This process continues until n reaches 0 or 1, at which point the function returns a or b respectively.
print(fibonacci_tail_recursive(7))
Finally, the function is called with n = 7, which computes the 7th term of the Fibonacci sequence using tail recursion. The result is printed to the console.
This code demonstrates a tail-recursive implementation of the Fibonacci sequence, where the recursive call is the last operation performed by the function. However, it's worth noting that Python's interpreter does not perform tail call optimization by default, so this tail-recursive implementation doesn't gain any performance benefits over a non-tail-recursive version in Python.
0 Comments:
Post a Comment