Last active
December 16, 2015 19:28
-
-
Save majgis/5484865 to your computer and use it in GitHub Desktop.
Answer to an interview question.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" Interview question | |
Write a method that takes a string, and returns the string in reverse. | |
For instance, if passed abc123 it should return 321cba | |
""" | |
class StringUtil(object): | |
""" Utility for strings | |
""" | |
def Reverse(self, string): | |
""" Returns the given string in reverse order """ | |
return string[::-1] | |
def Reverse2(self, string): | |
"""A less pythonic but more portable approach to reverse string order""" | |
position = len(string) - 1 | |
tempContainer = [] | |
while position >= 0: | |
element = string[position] | |
tempContainer.append(element) | |
position -= 1 | |
return ''.join(tempContainer) | |
if __name__ == '__main__': | |
import unittest | |
class StringUtilTestCase(unittest.TestCase): | |
"Test case for the StringUtil class" | |
def setUp(self): | |
"""Initial setup for all tests""" | |
self.su = StringUtil() | |
self.testString = 'abc123' | |
self.reversedString = '321cba' | |
def test_Reverse(self): | |
"""Test string reversal using the first method""" | |
testResult = self.su.Reverse(self.testString) | |
self.assertEqual(testResult, self.reversedString) | |
def test_Reverse2(self): | |
"""Test string reversal using the second method""" | |
testResult = self.su.Reverse2(self.testString) | |
self.assertEqual(testResult, self.reversedString) | |
unittest.main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment