Commits

Christoph Schindler  committed 06f25c5

8. Coding-Dojo: String Calculator

  • Participants
  • Parent commits 4e8da1c

Comments (0)

Files changed (2)

File StringCalculator/stringcalculator.py

+import re
+
+# sum(int(i.strip() or 0) for i in numbers.split(','))
+
+def add(numbers):
+    if numbers == "":
+        return 0
+        
+    regex = r"[,\n]"
+    if numbers.startswith("//"):
+        regex, numbers = numbers.split("\n", 1)
+        regex = re.escape(regex[2:])
+
+    return sum(int(i) for i in re.split(regex, numbers))

File StringCalculator/test_stringcalculator.py

+from nose.tools import assert_equal
+
+import stringcalculator
+
+def test_parse_empty_string():
+    assert_equal(stringcalculator.add(""), 0)
+
+def parse_single_digit(i):
+    assert_equal(stringcalculator.add(str(i)), i)
+
+def test_single_digit():
+    for i in range(10):
+        yield parse_single_digit, i
+        
+def test_multi_digit():
+    assert_equal(stringcalculator.add("1,2"),3)
+
+def test_42():
+    assert_equal(stringcalculator.add("42"), 42)
+    
+def test_newline():
+    assert_equal(stringcalculator.add("1\n2,3"), 6)
+    
+def test_custom_delimiter():
+    assert_equal(stringcalculator.add("//;\n2;3"), 5)
+    
+def test_dot_delimiter():
+    assert_equal(stringcalculator.add("//.\n2.3.4"), 9)
+    
+def test_multicharacter_delimiters_do_they_work_or_not():
+    assert_equal(stringcalculator.add("//hop\n30hop5hop1"), 36)
+