简体   繁体   English

如何计算为计算 Python 中 n 的阶乘而进行的递归调用次数

[英]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).我想编写一个名为recursive_factorial(n)的递归 function,它将非负 integer 作为参数并计算阶乘(n)的结果。 The function returns a tuple containing the result and the number of recursive calls made, in that order. function 返回一个元组,其中包含结果和递归调用的次数,按此顺序。

-- The first function call does not count as a recursive call. -- 第一个 function 调用不算作递归调用。

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:测试和 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 .如果你想计算递归调用的数量,你的期望是错误的,因为你没有计算n=1的调用。

To show you that with an example, let's immagine you call recursive_factorial(3) .为了通过示例向您展示这一点,让我们假设您调用了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由于您说您没有计算n=0的情况,因此预期的计数应该是 3,而不是您预期的 2

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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