Skip to content

Commit

Permalink
Merge pull request #52 from MIT-Emerging-Talent/factorial_36
Browse files Browse the repository at this point in the history
challenge: factorial_36
  • Loading branch information
MPKenley authored Jan 12, 2025
2 parents 88c2b2b + ef8102c commit ebeec70
Show file tree
Hide file tree
Showing 4 changed files with 66 additions and 0 deletions.
Empty file.
45 changes: 45 additions & 0 deletions solutions/challenge_36/factorial.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""factorial python module."""


def factorial(n):
"""
Calculate the factorial of a non-negative integer n using recursion.
Args:
n (int): Non-negative integer whose factorial is to be calculated.
Returns:
int: Factorial of the input number n. The return value must be greater than or equal to 1.
Raises:
ValueError: If n is a negative number.
Examples:
>>> factorial(0) # 0! = 1
1
>>> factorial(4) # 4! = 24
24
>>> factorial(-1)
Traceback (most recent call last):
...
ValueError: Factorial is not defined for negative numbers.
"""
if n < 0:
raise ValueError("Factorial is not defined for negative numbers.")
if n == 0:
return 1
return n * factorial(n - 1)


if __name__ == "__main__":
import doctest

print("running doctest...")
doctest.testmod(verbose=True)
try:
num = int(input("Enter a non-negative integer: "))
print(f"Factorial of {num} is {factorial(num)}")
except ValueError as e:
print(f"Error: {e}")
Empty file.
21 changes: 21 additions & 0 deletions solutions/tests/challenge_36/test_factorial.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
"""This unittest tests the python factorial program for positive numbers, negative numbers and zero"""

import unittest
from solutions.challenge_36.factorial import factorial


class TestFactorial(unittest.TestCase):
"""test the program for positive numbers, negative numbers and zero"""

def test_factorial_with_positive(self):
"""test factorial of 5."""
self.assertEqual(factorial(5), 120)

def test_factorial_with_zero(self):
"""test factorial of 0"""
self.assertEqual(factorial(0), 1)

def test_factorial_with_negative(self):
"""test factorial of -1"""
with self.assertRaises(ValueError):
factorial(-1)

0 comments on commit ebeec70

Please sign in to comment.