String Calculator Sample Python Code

Code:

class stringcalculator(object):
    
    def add(numbers, delimeter):
        result = 0
        if numbers == "": return result
        
        for value in str(numbers).split(delimeter):
            if not stringcalculator.__check_int(value): continue
            result += int(value)

        return result 

    def __check_int(s):
        if s == "": 
            return False
        if s[0] in ('-', '+'):
            return s[1:].isdigit()
        return s.isdigit()

Test:

class Test_stringcalculator(unittest.TestCase):
    def test_stringcalculator(self):
        testcases = {}
        testcases[""] = 0
        testcases[" "] = 0
        testcases[","] = 0
        testcases["dgdgdg"] = 0
        testcases["1,2"] = 3
        testcases["12"] = 12
        testcases["1gggd,2"] = 2
        testcases["asdad1,fgdgf,8"] = 8
        testcases["1,2,3"] = 6
        testcases["1,2,3,4,5,6,7,8,9"] = 45

        calc = stringcalculator.stringcalculator

        for key, value in testcases.items():
            result = calc.add(key, ",")
            self.assertEqual(value, result)