Added functions to check for palindromes and convert nums to bin strings

This commit is contained in:
2021-06-29 15:22:37 -04:00
parent 0bbb7ff9bf
commit 6ed905fa01
2 changed files with 51 additions and 2 deletions

View File

@@ -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)

View File

@@ -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
"""