After trying with Learn Python The Hard Way, I’m continuing with CodeAcademy. It’s fun to do some programming again. After mulling over something significantly challenging for my rusty gears, I decided to solve the problem of converting numbers to text.
The hardest bit was taking the time to think through the issue. I committed the error of coding without thinking. Perhaps the only intelligent thing I did in phase I was working out the mydict dictionary, which did not need to be changed throughout, except that I added trillion to it.
So here’s the code without much ado. When prompted to enter a number, enter just numbers.
E.g.:
Enter a number:832743242
Eight Hundred Thirty Two Million Seven Hundred Forty Three Thousand Two Hundred Forty Two
mydict = {0:"",
1:"one",
2:"two",
3:"three",
4:"four",
5:"five",
6:"six",
7:"seven",
8:"eight",
9:"nine",
10:"ten",
11:"eleven",
12:"twelve",
13:"thirteen",
14:"fourteen",
15:"fifteen",
16:"sixteen",
17:"seventeen",
18:"eighteen",
19:"nineteen",
20:"twenty",
30:"thirty",
40:"forty",
50:"fifty",
60:"sixty",
70:"seventy",
80:"eighty",
90:"ninety",
100:"hundred",
1000:"thousand",
1000000:"million",
1000000000:"billion",
1000000000000:"trillion"
}
def to_text2(num,units=1):
#have to split the number into thousands
low = num % 1000
high = int(num /1000)
#evaluate the lower part
low_str = ""
if low!=0:
hundred = int(low / 100)
#print h
if hundred!=0:
low_str = mydict.get(hundred) +" "+ mydict.get(100)
tens = (low %100)
if tens<=20:
if tens!=0:
low_str = low_str + " " + mydict.get(tens)
else:
low_str = low_str+ " " + mydict.get(int(tens/10)*10) + " " + mydict.get(tens%10)
if units!=1:
if low_str!="":
low_str =low_str + " " + mydict.get(units)
if high!=0:
return to_text2(high,units*1000) + " " + low_str.strip()
else:
return low_str.strip()
input_number = eval(raw_input("Enter a number:"))
print to_text2(input_number).title()
