[Tutor] Text numerals?

Bob Gailer bgailer at alum.rpi.edu
Sun May 16 12:26:52 EDT 2004


At 11:42 PM 5/15/2004, Don Arnold wrote:


> > Is there a function that will return 'one' for 1, 'two' for two, etc.?
> >
>
>   I assume you mean 'two' for 2 ;).  But no, AFAIK there is no stdlib
>implementation.
>
><snip dictionary suggestions>
>
>   The problem of converting full-blown numbers of any length into letters is
>much harder.  Some years ago I remember this being coded in python; if the
>author has a website, then Google is probably your best bet.
>
>   But make sure you need that kind of complexity; better to have a solution
>you understand than one which is too powerful that you don't.  It helps when
>things go wrong ;).
>
>--
>Glen
>
>
>my reply:
>
>Good advice, but this problem turned out not to be as complex as it first
>appeared. Really, all you need to do is pad the number to a length that's
>divisible by 3 and then start processing digits from the left, three at a
>time. Here's my take on it:

In the (for me) inevitable pursuit of programming alternatives, here's a 
list/numeric version of Don's solution.

littleNumbers = [' ', 'one', 'two', 'three', 'four', 'five', 'six', 'seven',
                  'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen',
                  'fourteen', 'fifteen', 'sixteen', 'seventeen', 
'eighteen', 'nineteen']

tens = ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 
'eighty', 'ninety']

groupings = ['', ' thousand', ' million', ' billion', ' trillion', ' 
quadrillion',
              ' quintillion', ' sextillion', ' septillion', ' octillion', ' 
nonillion', ' decillion']

def main(num):
   maxGroups = 12
   maxDigits = maxGroups * 3
   if num >= 10**maxDigits:raise 'Number must have at most %s digits.' % 
(maxDigits,)
   result = []
   sign = ('', 'negative ')[num<0]
   num = abs(num)
   groupSep = ''
   for group in range(0,12):
     if not num: break
     num, thousandsGroup = divmod(num, 1000)
     if thousandsGroup:
       if group:result.append(groupings[group] + groupSep)
       groupSep = ', '
       hundred, unitTen = divmod(thousandsGroup, 100)
       if unitTen < 20:
         result.append(littleNumbers[unitTen])
       else:
         result.append(littleNumbers[unitTen%10])
         if unitTen%10: result.append('-')
         result.append(tens[unitTen/10])
       if hundred:
         result.append(littleNumbers[hundred] + ' hundred ')
   result.reverse()
   return sign + ''.join(result) or 'zero'
[snip]

Bob Gailer
bgailer at alum.rpi.edu
303 442 2625 home
720 938 2625 cell  




More information about the Tutor mailing list