The challenge
Create a function that takes 2 nonnegative integers in form of a string as an input, and outputs the sum (also as a string):
Example: (Input1, Input2 –>Output)
"4", "5" --> "9"
"34", "5" --> "39"
Notes:
- If either input is an empty string, consider it as zero.
- Inputs and the expected output will never exceed the signed 32-bit integer limit (
2^31 - 1
)
The solution in Python code
Option 1:
def sum_str(a, b):
return str(int(a or 0) + int(b or 0))
Option 2:
def sum_str(*values):
return str(sum(int(s or '0') for s in values))
Option 3:
def sum_str(*args):
return str(sum(map(lambda x: int(x) if x else 0, args)))
Test cases to validate our solution
import test
from solution import sum_str
@test.describe("Fixed Tests")
def basic_tests():
@test.it("Sample Tests")
def sample_tests():
test.assert_equals(sum_str("4","5"), "9")
test.assert_equals(sum_str("34","5"), "39")
@test.it("Tests with empty strings")
def empty_string():
test.assert_equals(sum_str("9",""), "9", "x + empty = x")
test.assert_equals(sum_str("","9"), "9", "empty + x = x")
test.assert_equals(sum_str("","") , "0", "empty + empty = 0")