Created
March 13, 2017 13:37
-
-
Save jbq/599919d4ae3d9faae0cdb4d979aab863 to your computer and use it in GitHub Desktop.
Python Calculator
This file contains hidden or 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
#! /usr/bin/python3 | |
import unittest | |
class NegativeNumber(Exception): | |
pass | |
class Calculator: | |
def add(self, numbers: str) -> int: | |
self.negatives = [] | |
if (len(numbers) == 0): | |
return 0 | |
delimiter = "," | |
if (numbers.startswith("//")): | |
pieces = numbers.split("\n") | |
# take delimiter on first line | |
delimiter = pieces[0].replace("//", "") | |
print("delimiter", delimiter) | |
# normalize input to replace all newlines by the specified delimiter to avoid regexps | |
numbers = delimiter.join(pieces[1:]) | |
else: | |
# normalize input to replace all newlines by the specified delimiter to avoid regexps | |
numbers = numbers.replace("\n", delimiter) | |
print("numbers", numbers) | |
array_strings = numbers.split(delimiter) | |
print("array_strings", array_strings) | |
nb = sum([self.toint(x) for x in array_strings]) | |
if len(self.negatives) > 0: | |
raise NegativeNumber("Negatives are not allowed: %s" % ", ".join(self.negatives)) | |
return nb | |
def toint(self, x): | |
xx = int(x) | |
if (xx < 0): | |
self.negatives.append(x) | |
if (xx > 1000): | |
return 0 | |
return xx | |
class Test(unittest.TestCase): | |
def testCalculator(self): | |
calc = Calculator() | |
self.assertEqual(0, calc.add("")) | |
self.assertEqual(1, calc.add("1")) | |
self.assertEqual(3, calc.add("1\n2")) | |
self.assertEqual(6, calc.add("1\n2,3")) | |
try: | |
calc.add("1,\n") | |
except ValueError: | |
# This is OK | |
pass | |
self.assertEqual(6, calc.add("//+\n1+2+3")) | |
self.assertEqual(6, calc.add("//\\\n1\\2\\3")) | |
try: | |
calc.add("-1") | |
except NegativeNumber as e: | |
self.assertEqual("Negatives are not allowed: -1", str(e)) | |
try: | |
calc.add("-1,0,-2") | |
except NegativeNumber as e: | |
self.assertEqual("Negatives are not allowed: -1, -2", str(e)) | |
self.assertEqual(6, calc.add("1,2,1001,3")) | |
# 7. delimiter in any format | |
self.assertEqual(6, calc.add("//***\n1***2***3")) | |
if __name__ == '__main__': | |
unittest.main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment