請幫助我理解我哪裏錯了:階乘遞歸和迭代
這是一個問題:同時創建一個遞歸函數調用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(N):'已經沒有'return' – Psytho
你可以添加一些調試打印的結果'recursive_factorial(0)'。代碼看起來正確。 –