请帮助我了解我哪里出错了:
问题是:创建一个称为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
请帮助我了解我出了错。
您忘记了return x
from iterative_factorial()
,因此函数隐式返回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))