Skip to content

Instantly share code, notes, and snippets.

@mpurdon
Last active July 7, 2016 05:16
Show Gist options
  • Save mpurdon/c6b6aea4f914f6dfacc4 to your computer and use it in GitHub Desktop.
Save mpurdon/c6b6aea4f914f6dfacc4 to your computer and use it in GitHub Desktop.
Parse numbers from strings and sum them
"""
Proof of concept
Someone wanted to parse number from random strings and sum them as part of some school project.
@author: Matthew Purdon
"""
from __future__ import print_function
import sys
def parse_string(string):
result = 0
sign = 1
numbers = []
current_number = ''
for character in string:
print("Processing character {}".format(character))
if character.isdigit():
print("+++ appended to current number")
current_number += character
else:
if character == '-':
print("--- negating current number")
sign = -1
continue
if current_number:
current_number = sign * int(current_number)
print ("*** appending {} to list of numbers".format(current_number))
numbers.append(current_number)
sign = 1
current_number = ''
continue
if current_number:
current_number = sign * int(current_number)
print ("*** appending {} to list of numbers".format(current_number))
numbers.append(current_number)
print("Summing numbers {}".format(numbers))
return sum(numbers)
def main():
strings = [
"--1a2b-3c",
"123ab!45c",
"abcdef",
"0123.4",
"dFD$#23+++12@#T1234;/.,10",
]
for string in strings:
print ("{} = {}\n\n".format(string, parse_string(string)))
return 0
if __name__ == "__main__":
sys.exit(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment