简体   繁体   中英

factorial recursion and iteration in python

please help me understand where i went wrong:

this is the question:Create both a recursive function called recursive_factorial and iterative function called iterative_factorial that does the following

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

this is the test i am using for the question:

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")

this is the code i have written:

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

this is the error i am getting:

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 

please help me understand where i went wrong.

You're forgetting to return x from iterative_factorial() , so the function is implicitly returning None .

As an aside, you can iterate of the result of range() directly:

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

Finally, this might be a good opportunity to learn about Python's reduce() function.

import operator

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

iterative_factorial needs to end with

    return x


Also, iterative_factorial doesn't need li . Better to just write:

    for each in range(1,n+1):
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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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