天天看点

python用递归和迭代求n的阶乘_python中的阶乘递归与迭代

请帮助我理解我错在哪里:

这是一个问题:创建一个称为递归析因的递归函数和一个称为迭代析因的迭代函数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

这是我得到的错误:

一。迭代因式检验Failure in line 21, in test_iterative_factorial_one self.assertEqual(result, 120, msg="Inaccurate value") AssertionError: Inaccurate value

2。检验迭代因子二Failure in line 25, in test_iterative_factorial_two self.assertEqual(result, 1, msg="Inaccurate value") AssertionError: Inaccurate value

请帮助我理解我错在哪里。