Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

shit challenge: numerics to words

Name: Anonymous 2010-07-25 3:01

Weekly Challenge: Programmatically convert any1 string of digits, such as "1234567" to word form, "one million, two hundred thirty-four thousand, five hundred sixty-seven"

Here is mine: http://codepad.org/gyqbaKxx

Criticize my code.  I know it sucks anus.  I would like to make it better.  Submit your own versions as well.

Use whatever language you like[i]!/i]

_____________________________________
1. Up to 18 significant digits is fine.

Name: Anonymous 2010-07-27 23:18

I decided to give this a go. I steered clear of looking at any of the other posts and came up with what follows. This could very easily be rewritten in C.


def num_to_name( num_str ):
    global exact, tens, powers
    # Convert to int and back, which fixes whitespace and leading zeroes.
    try:
        num_str = str(int(num_str))
    except ValueError:
        return "That was not a number!"
   
    if num_str == "0":
        return "zero"
   
    strlen = len(num_str)
   
    if strlen > 18 + 1 :
        return "That number is too large for my puny brain!"
   
    ans = [] # List to hold number words.
   
    i = -1
    while i < (strlen - 1):
        i += 1
       
        if num_str[i] != "0":
            m = (strlen - i - 1) % 3
       
            if m == 2:
                # Hundreds
                ans.append( exact[ num_str[i] ] )
                ans.append( "hundred " )
                continue
           
            elif m == 1:
                # Tens
                if num_str[i] == "1":
                    ans.append( exact[ num_str[i:i+2] ] )
                    i += 1
                else:
                    ans.append ( tens[ num_str[i] ] )
                    continue
            else:
                # Ones
                ans.append( exact[ num_str[i] ] )
       
        # Powers
        o = strlen - i - 1
               
        if o and not (o % 3) :
            ans.append( powers[o] )
                   
   
    return "".join(ans).rstrip(" ,")

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List