Converting a string into integers

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • AuroraBorealis
    New Member
    • Oct 2009
    • 4

    Converting a string into integers

    I have to write this short program that converts digits/symbols in a string into integers. Basically it takes a string containing none or one operation sign "+" or "-" if __init__ allows it, followed by one or more digits, and can contain blank spaces anywhere. It then returns a triple in this format:

    (number of characters in the string including blanks, but not including blanks after the digits, "-1" if there was a "-" right before the digits with no spaces as gap otherwise "1", the integer in the string)

    ["_" means a blank space]
    So "__-" would return (0, 1, 0) since there are no digits
    "__+1" would return (4, 1, 1)
    "+1" would return (2, 1, 1)
    "__-1" would return (4, -1, -1)
    "-1" would return (2, -1, -1)
    "__+_1" would return (5, 1, 1)
    "__-_1" would return (5, 1, 1) since there was a gap between "-" and "1"
    "_1-" would return (3, 1, 1) since "-" is in the wrong place
    and "_+1___abcd e" would return (3, 1, 1) since blank spaces after the digits are ignored and letters are ignored

    For the __init__ method, how do create this scanner, and set up whether or not "+" and "-" signs are allowed?
    So far I have:

    Code:
    class ConvertToTriple(object):
         
         def __init__(self, take_sign):
              '''Create scanner that converts strings to integers, and accepts leading "+" or "-" signs if take_sign is True.'''
    
         def scan_string(self, s):
              '''Scan a character from string s.'''
    How would I set up the __init__ method?
    Thanks for any tips.
  • Glenton
    Recognized Expert Contributor
    • Nov 2008
    • 391

    #2
    Well, I'd start with an algorithm, and then try to code it.

    Can you devise an algorithm that would do what you want?

    Comment

    Working...