Skip to content

Instantly share code, notes, and snippets.

@lamchau
Created March 3, 2014 04:40
Show Gist options
  • Save lamchau/9318472 to your computer and use it in GitHub Desktop.
Save lamchau/9318472 to your computer and use it in GitHub Desktop.
simple interview questions with unittests (pyunit)
#/usr/bin/python env
import abc
import unittest
class StringUtilities(object):
@staticmethod
def is_palindrome(s):
if not isinstance(s, str):
return False
s = [x.lower() for x in s if x.isalnum()]
length = len(s)
for x in range(length >> 1):
if s[x] != s[length - x - 1]:
return False
return True if length else False
@staticmethod
def reverse(s):
# using API
# return s[::-1]
if not isinstance(s, str):
return
s = list(s)
length = len(s)
for x in range(length >> 1):
index = length - 1 - x
s[x], s[index] = s[index], s[x]
return "".join(s)
class BaseTest(unittest.TestCase):
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def _test(self, input):
raise NotImplementedError
@classmethod
def runner(cls, test_cases):
def test(value, expected):
return lambda self: self._test(value, expected)
for value, expected in test_cases:
test_name = "test_%s" % str(value)
setattr(cls, test_name, test(value, expected))
class TestPalindrome(BaseTest):
def _test(self, value, expected):
result = StringUtilities.is_palindrome(value)
if expected:
self.assertTrue(result)
else:
self.assertFalse(result)
class TestReverse(BaseTest):
def _test(self, value, expected):
result = StringUtilities.reverse(value)
self.assertEqual(result, expected)
TestPalindrome.runner([
("", False),
("abc", False),
("madam", True),
("Madam", True),
(None, False),
(1221, False),
("1221", True),
("12.21", True),
("A man, a plan, a canal, Panama!", True)
])
TestReverse.runner([
("abc", "cba"),
("12", "21"),
(None, None)
])
if __name__ == "__main__":
runner = unittest.TextTestRunner(verbosity=2)
unittest.main(testRunner=runner)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment