From 6ed905fa01ff129d01830821c4201619ee6ed66b Mon Sep 17 00:00:00 2001 From: Mattrixwv Date: Tue, 29 Jun 2021 15:22:37 -0400 Subject: [PATCH] Added functions to check for palindromes and convert nums to bin strings --- Algorithms.py | 13 +++++++++++++ TestAlgorithms.py | 40 ++++++++++++++++++++++++++++++++++++++-- 2 files changed, 51 insertions(+), 2 deletions(-) diff --git a/Algorithms.py b/Algorithms.py index c81a64b..c8bd384 100644 --- a/Algorithms.py +++ b/Algorithms.py @@ -236,3 +236,16 @@ def factorial(num: int) -> int: for cnt in range(1, num + 1): fact *= cnt return fact + +#Returns true if the string passed in is a palindrome +def isPalindrome(str: str) -> bool: + rev = str[::-1] + if(str == rev): + return True + else: + return False + +#Converts a number to its binary equivalent +def toBin(num: int) -> str: + #Convert the number to a binary string + return "{0:b}".format(num) diff --git a/TestAlgorithms.py b/TestAlgorithms.py index 629b3de..7f037e2 100644 --- a/TestAlgorithms.py +++ b/TestAlgorithms.py @@ -161,15 +161,51 @@ class TestAlgorithms(unittest.TestCase): answer = Algorithms.factorial(num) self.assertEqual(correctAnswer, answer, "getFactorial failed the third test") + #This function tests the isPalindrome function + def testIsPalindrome(self): + #Test 1 + str = "101" + correctAnswer = True + answer = Algorithms.isPalindrome(str) + self.assertEqual(correctAnswer, answer, "isPalindrome failed the first test") + #Test 2 + str = "100" + correctAnswer = False + answer = Algorithms.isPalindrome(str) + self.assertEqual(correctAnswer, answer, "isPalindrome failed the second test") + #Test 3 + str = "" + correctAnswer = True + answer = Algorithms.isPalindrome(str) + self.assertEqual(correctAnswer, answer, "isPalindrome failed the third test") + + #This function tests the toBin function + def testToBin(self): + #Test 1 + num = 7 + correctAnswer = "111" + answer = Algorithms.toBin(num) + self.assertEqual(correctAnswer, answer, "toBin failed the first test") + #Test 2 + num = 0 + correctAnswer = "0" + answer = Algorithms.toBin(num) + self.assertEqual(correctAnswer, answer, "toBin failed the second test") + #Test 3 + num = 1000000 + correctAnswer = "11110100001001000000" + answer = Algorithms.toBin(num) + self.assertEqual(correctAnswer, answer, "toBin failed the third test") + #Run the unit test if the script is called if __name__ == "__main__": unittest.main() """Results: -.......... +............ ---------------------------------------------------------------------- -Ran 10 tests in 0.003s +Ran 12 tests in 0.002s OK """