I want to write a recursive function named recursive_factorial(n) that takes a non-negative integer as a parameter and calculates the result of factorial(n). The function returns a tuple containing the result and the number of recursive calls made, in that order.
— The first function call does not count as a recursive call.
def recursive_factorial(n):
if n == 0:
return 1, 0
else:
value,step = recursive_factorial(n-1)
return n * value, step + 1
Test and Output:
>> print(recursive_factorial(1))
(1, 0) --- Expected
(1, 1) --- Gotten
>> print(recursive_factorial(3))
(6, 2) --- Expected
(6, 3) --- Gotten
>> print(recursive_factorial(8))
(40320, 7) --- Expected
(40320, 8) --- Gotten
>Solution :
If you want to count the number of recursive calls, your expectations are wrong since you’re not counting the call with n=1.
To show you that with an example, let’s immagine you call recursive_factorial(3). The stack of calls will be
recursive_factorial(3)recursive_factorial(2)recursive_factorial(1)recursive_factorial(0)
Since you said you’re not counting the case with n=0, the expected count should be 3, not 2 as you would have expected
If you want the counter to match the current expectation you have to add another base case
def recursive_factorial(n):
if n == 0 or n ==1:
return 1, 0
else:
value,step = recursive_factorial(n-1)
return n * value, step + 1