Skip to content

Add recursive factorial method with tests #12800

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Empty file added recursion/__init__.py
Empty file.
30 changes: 30 additions & 0 deletions recursion/factorial.py
Original file line number Diff line number Diff line change
@@ -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)
Empty file added recursion/tests/__init__.py
Empty file.
15 changes: 15 additions & 0 deletions recursion/tests/test_factorial.py
Original file line number Diff line number Diff line change
@@ -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)
Loading