python中的阶乘递归和迭代

时间:2016-01-08 11:42:52

标签: python recursion

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

这是一个问题:创建一个名为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 

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

3 个答案:

答案 0 :(得分:4)

您忘记return x iterative_factorial(),因此功能为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))

答案 1 :(得分:1)

iterative_factorial需要以

结尾
    return x


此外,iterative_factorial不需要li。最好只写:

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

答案 2 :(得分:0)

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(2, n+1))
    for each in li:
        x = x*each
        yield x