Skip to content

Commit 4c7cc73

Browse files
committed
Add recursive factorial method with tests
1 parent c3d4b9e commit 4c7cc73

File tree

4 files changed

+46
-0
lines changed

4 files changed

+46
-0
lines changed

recursion/__init__.py

Whitespace-only changes.

recursion/factorial.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
"""
2+
Fibonacci
3+
https://en.wikipedia.org/wiki/Fibonacci_number
4+
"""
5+
def factorial(number: int) -> int:
6+
"""
7+
Compute the factorial of a non-negative integer using recursion.
8+
9+
>>> factorial(5)
10+
120
11+
>>> factorial(0)
12+
1
13+
>>> factorial(1)
14+
1
15+
>>> factorial(3)
16+
6
17+
>>> factorial(10)
18+
3628800
19+
>>> factorial(-1)
20+
Traceback (most recent call last):
21+
...
22+
ValueError: Input must be a non-negative integer.
23+
"""
24+
if number < 0:
25+
raise ValueError("Input must be a non-negative integer.")
26+
if number == 0:
27+
return 1
28+
return number * factorial(number - 1)

recursion/tests/__init__.py

Whitespace-only changes.

recursion/tests/test_factorial.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import unittest
2+
from recursion.factorial import factorial
3+
4+
5+
class TestFactorial(unittest.TestCase):
6+
def test_factorial_valid_inputs(self):
7+
self.assertEqual(factorial(0), 1)
8+
self.assertEqual(factorial(1), 1)
9+
self.assertEqual(factorial(5), 120)
10+
self.assertEqual(factorial(10), 3628800)
11+
12+
def test_factorial_invalid_input(self):
13+
with self.assertRaises(ValueError):
14+
factorial(-1)
15+
16+
17+
if __name__ == "__main__":
18+
unittest.main()

0 commit comments

Comments
 (0)