John Machin wrote:
Stephen Thorne wrote:
.def toNumber2(s):
.   items = s.replace(',', '').split()
.   numbers = [translation.get(item.strip(), -1) for item in items if
item.strip()]
.   stack = [0]
.   for num in numbers:
.      if num == -1:
.         raise ValueError("Invalid string '%s'" % (s,))
.      if num >= 100:
.         stack[-1] *= num
.         if num >= 1000:
.            stack.append(0)
.      else:
.         stack[-1] += num
.   return sum(stack)


Can I play too? Let's replace the top with some little bit of error handling:

    def toNumber3(text):
        s = text.replace(',', '').replace('-', '')# for twenty-three
        items = s.split()
        try:
            numbers = [translation[item] for item in items]
        except KeyError, e:
            raise ValueError, "Invalid element %r in string %r" % (
                               e.args[0], text)
        stack = [0]
        for num in numbers:
            if num >= 100:
                stack[-1] *= num
                if num >= 1000:
                    stack.append(0)
            else:
                stack[-1] += num
        return sum(stack)

--Scott David Daniels
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to