faqts : Computers : Programming : Languages : Python

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

1 of 1 people (100%) answered Yes
Recently 1 of 1 people (100%) answered Yes

Entry

How can I get Python to spell out numbers 0-999 using dictionaries, but not entering every number?

Sep 27th, 2007 23:52
Reed O'Brien, gina martin,


>>> tr = dict(zip([0,1,2,3,4,5,6,7,8,9], ['zero', 'one', 'two', 'three',
'four', 'five', 'six', 'seven', 'eight', 'nine']))

>>> for number in range(1000):
    print ' '.join([tr[int(x)] for x in str(number)])
...     
...     
zero
one
two
three
four
five
six
seven
eight
nine
one zero
one one
one two
one three
one four
one five
...
nine nine six
nine nine seven
nine nine eight
nine nine nine

I imagine you can fairly easily duse an array or another trick to map
ordinality to column positions. 

 * map ten, twenty, thirty, ... to the second column
 * append ' hundred' to the third column

and so forth.

>>> c1 = dict(zip([0,1,2,3,4,5,6,7,8,9], ['zero', 'one', 'two', 'three',
'four', 'five', 'six', 'seven', 'eight', 'nine']))
>>> c2 = dict(zip([0,1,2,3,4,5,6,7,8,9], ['oh', 'ten', 'twenty',
'thirty', 'fourty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety']))

>>> c3 = dict(zip([0,1,2,3,4,5,6,7,8,9], ['???', c1[1] +'hundred', c1[2]
+ ' hundred', c1[3] + ' hundred', c1[4] + ' hundred', c1[5] + '
hundred', c1[6] + ' hundred', c1[7] + ' hundred', c1[8] + ' hundred',
c1[9] + ' hundred']))

>>> cols = [c1, c2, c3]   

>>> for number in range(1000):
    L = list(str(number))
    pos = len(L)-1
    text = []
    for item in L:
        text.append(cols[pos][int(item)])
        pos -=1
    print number, ' = ', ' '.join(text)
...     
...     
0  =  zero
1  =  one
2  =  two
3  =  three
...
993  =  nine hundred ninety three
994  =  nine hundred ninety four
995  =  nine hundred ninety five
996  =  nine hundred ninety six
997  =  nine hundred ninety seven
998  =  nine hundred ninety eight
999  =  nine hundred ninety nine


I leave it to you to fix up the zero at the end of ten zero, twenty zero
etc...