Last active
July 2, 2017 18:02
-
-
Save akost/b4223a02158c8aa45441f9a187c7868a to your computer and use it in GitHub Desktop.
Converts string to integer
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
""" | |
Convert string to integer | |
""" | |
import unittest | |
class TestStringMethods(unittest.TestCase): | |
def test1(self): | |
self.assertEqual(myInt("123"), 123) | |
def test2(self): | |
self.assertEqual(myInt("-1"), -1) | |
def test3(self): | |
self.assertEqual(myInt("0"), 0) | |
def test4(self): | |
self.assertEqual(myInt("-0"), 0) | |
def test5(self): | |
self.assertRaises(TypeError, myInt, "") | |
def test6(self): | |
self.assertRaises(TypeError, myInt, "12q3") | |
def myInt(s): | |
num = 0 | |
l = len(s) | |
if l == 0: | |
raise TypeError("String must be non-empty") | |
sign = 1 | |
if s[0] == "-": | |
sign = -1 | |
s = s[1:] | |
for i in s: | |
if ord(i) in range(ord("0"), ord("9") + 1): | |
digit = ord(i) - ord("0") | |
num = num*10 + digit | |
else: | |
raise TypeError("String must contain only digits and minus sign") | |
return sign * num | |
unittest.main() | |
print myInt("-112490") # -112490 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment