Skip to main content
 首页 » 编程设计

python之python中的阶乘递归和迭代

2025年05月04日14mfryf

请帮助我了解我哪里出错了:

问题是:创建一个名为 recursive_factorial 的递归函数和一个名为 iterative_factorial 的迭代函数,它执行以下操作

Accepts as parameter an Integer n 
Computes the factorial of n 
Returns the factorial of n 

这是我为这个问题使用的测试:

import unittest 
 
class RecursiveTestCase(unittest.TestCase): 
 
  def test_recursive_factorial_one(self): 
    result = recursive_factorial(4) 
    self.assertEqual(result, 24, msg="Inaccurate value") 
 
  def test_recursive_factorial_two(self): 
    result = recursive_factorial(0) 
    self.assertEqual(result, 1, msg="Inaccurate value") 
 
  def test_iterative_factorial_one(self): 
    result = iterative_factorial(5) 
    self.assertEqual(result, 120, msg="Inaccurate value") 
 
  def test_iterative_factorial_two(self): 
    result = iterative_factorial(0) 
    self.assertEqual(result, 1, msg="Inaccurate value") 

这是我写的代码:

def recursive_factorial(n): 
    if n == 0: 
        return 1 
    else: 
        return n * recursive_factorial(n-1) 
def iterative_factorial(n): 
    x = 1 
    li = list(range(1, n + 1)) 
    for each in li: 
        x = x * each 

这是我遇到的错误:

1 。 test_iterative_factorial_one

Failure in line 21, in test_iterative_factorial_one self.assertEqual(result, 120, msg="Inaccurate value") AssertionError: Inaccurate value 

2。 test_iterative_factorial_two

Failure in line 25, in test_iterative_factorial_two self.assertEqual(result, 1, msg="Inaccurate value") AssertionError: Inaccurate value  

请帮助我了解哪里出了问题。

请您参考如下方法:

您忘记从 iterative_factorial() 中返回 x,所以函数是 implicitly returning None .

顺便说一句,您可以直接迭代 range() 的结果:

for each in range(1, n + 1): 
   ... 

最后,这可能是学习 Python 的 reduce() 的好机会功能。

import operator 
 
def another_iterative_factorial(n): 
   return reduce(operator.mul, range(1, n + 1))