Added function to get factorial of number

This commit is contained in:
2021-06-01 18:31:10 -04:00
parent a7c4346af5
commit 0bbb7ff9bf
2 changed files with 30 additions and 3 deletions

View File

@@ -229,3 +229,10 @@ def gcd(num1: int, num2: int) -> int:
else:
num2 %= num1
return num1 | num2
#Returns the factorial of the number passed in
def factorial(num: int) -> int:
fact = 1
for cnt in range(1, num + 1):
fact *= cnt
return fact

View File

@@ -1,7 +1,7 @@
#Python/pyClasses/TestAlgorithms.py
#Matthew Ellison
# Created: 01-27-19
#Modified: 03-11-21
#Modified: 06-01-21
#This is a file that contains a few algorithms that I have used several times
"""
Copyright (C) 2021 Matthew Ellison
@@ -141,15 +141,35 @@ class TestAlgorithms(unittest.TestCase):
answer = Algorithms.gcd(num1, num2)
self.assertEqual(correctAnswer, answer, "getGCD failed the third test")
#This functions tests the factorial function
def testFactorial(self):
#Test 1
num = 1
correctAnswer = 1
answer = Algorithms.factorial(num)
self.assertEqual(correctAnswer, answer, "getFactorial failed the first test")
#Test 2
num = 10
correctAnswer = 3628800
answer = Algorithms.factorial(num)
self.assertEqual(correctAnswer, answer, "getFactorial failed the second test")
#Test 3
num = -5
correctAnswer = 1
answer = Algorithms.factorial(num)
self.assertEqual(correctAnswer, answer, "getFactorial failed the third test")
#Run the unit test if the script is called
if __name__ == "__main__":
unittest.main()
"""Results:
.........
..........
----------------------------------------------------------------------
Ran 9 tests in 0.002s
Ran 10 tests in 0.003s
OK
"""