简体   繁体   中英

How to count the number of recursive calls made to calculate the factorial of n in Python

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

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

  1. recursive_factorial(3)
  2. recursive_factorial(2)
  3. recursive_factorial(1)
  4. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM