mirror of
https://bitbucket.org/Mattrixwv/pyclasses.git
synced 2025-12-06 18:33:58 -05:00
Added functions to check for palindromes and convert nums to bin strings
This commit is contained in:
@@ -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)
|
||||
|
||||
@@ -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
|
||||
"""
|
||||
|
||||
Reference in New Issue
Block a user