diff --git a/recursion/__init__.py b/recursion/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/recursion/factorial.py b/recursion/factorial.py new file mode 100644 index 000000000000..0fe09e2005bf --- /dev/null +++ b/recursion/factorial.py @@ -0,0 +1,30 @@ +""" +Fibonacci +https://en.wikipedia.org/wiki/Fibonacci_number +""" + + +def factorial(number: int) -> int: + """ + Compute the factorial of a non-negative integer using recursion. + + >>> factorial(5) + 120 + >>> factorial(0) + 1 + >>> factorial(1) + 1 + >>> factorial(3) + 6 + >>> factorial(10) + 3628800 + >>> factorial(-1) + Traceback (most recent call last): + ... + ValueError: Input must be a non-negative integer. + """ + if number < 0: + raise ValueError("Input must be a non-negative integer.") + if number == 0: + return 1 + return number * factorial(number - 1) diff --git a/recursion/tests/__init__.py b/recursion/tests/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/recursion/tests/test_factorial.py b/recursion/tests/test_factorial.py new file mode 100644 index 000000000000..91bcc2bb2c61 --- /dev/null +++ b/recursion/tests/test_factorial.py @@ -0,0 +1,15 @@ +import pytest + +from recursion.factorial import factorial + + +def test_factorial_valid_inputs() -> None: + assert factorial(0) == 1 + assert factorial(1) == 1 + assert factorial(5) == 120 + assert factorial(10) == 3628800 + + +def test_factorial_invalid_input() -> None: + with pytest.raises(ValueError): + factorial(-1)