Skip to content

Commit

Permalink
for PR
Browse files Browse the repository at this point in the history
  • Loading branch information
MPKenley committed Jan 9, 2025
1 parent e906db8 commit f1df2d9
Show file tree
Hide file tree
Showing 4 changed files with 50 additions and 0 deletions.
Empty file.
26 changes: 26 additions & 0 deletions solutions/challenge_36/factorial.py
Original file line number Diff line number Diff line change
@@ -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}")
Empty file.
24 changes: 24 additions & 0 deletions solutions/tests/challenge_36/test_factorial.py
Original file line number Diff line number Diff line change
@@ -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)

0 comments on commit f1df2d9

Please sign in to comment.