diff --git a/solutions/challenge_36/__init__.py b/solutions/challenge_36/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/solutions/challenge_36/factorial.py b/solutions/challenge_36/factorial.py new file mode 100644 index 000000000..b906ec0d8 --- /dev/null +++ b/solutions/challenge_36/factorial.py @@ -0,0 +1,26 @@ +"""this function allows to calculate the factorial of a non-negative integer n using recursive function""" + + +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. + """ + 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__": + 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}") diff --git a/solutions/tests/challenge_36/__init__.py b/solutions/tests/challenge_36/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/solutions/tests/challenge_36/test_factorial.py b/solutions/tests/challenge_36/test_factorial.py new file mode 100644 index 000000000..510e05133 --- /dev/null +++ b/solutions/tests/challenge_36/test_factorial.py @@ -0,0 +1,24 @@ +"""test the program factorial""" + +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_positive(self): + """test the program for positive numbers""" + self.assertEqual(factorial(5), 120) + self.assertEqual(factorial(4), 24) + self.assertEqual(factorial(3), 6) + self.assertEqual(factorial(1), 1) + + def test_factorial_zero(self): + """test the program for zero""" + self.assertEqual(factorial(0), 1) + + def test_factorial_negative(self): + """test the program for negative numbers""" + with self.assertRaises(ValueError): + factorial(-1)