Skip to content

Instantly share code, notes, and snippets.

@AChep
Created February 12, 2019 20:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AChep/2add2e0f786d9a7488837a8c0d324cbf to your computer and use it in GitHub Desktop.
Save AChep/2add2e0f786d9a7488837a8c0d324cbf to your computer and use it in GitHub Desktop.
This is a String Calculator
import re
def add(text):
"""
String Calculator
http://osherove.com/tdd-kata-1/
"""
if not text:
return 0
text = text.split('\n')
total = 0
pattern = None
for line in text:
if not pattern:
if line.startswith('//'):
delimeters_cst = [e[1:-1] for e in re.findall(r'\[.+?\]', line)]
if not delimeters_cst:
delimeters_cst = [line[2:]]
delimeters = delimeters_cst
skip_line = True
else:
delimeters = [',']
skip_line = False
delimeters = [re.escape(e) for e in delimeters]
pattern = '|'.join([e for e in delimeters])
if skip_line:
continue
numbers = re.split(pattern, line)
for number in numbers:
number_int = int(number)
if number_int < 1000:
total += number_int
return total
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment