Number to English Words
Write a program to convert a non-negative integer
The input will be a single line containing an integer
The output should be a single line containing the representation of the English words of number
For example, if the given number is 123, your code should print the English words representation, which is
One Hundred Twenty Three
Sample Input 1
123
Sample Output 1
One Hundred Twenty Three
Sample Input 2
10005
Sample Output 2
Ten Thousand Five
Sample Input 3
1234567891
Sample Output 3
One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One
def num_to_words(n:int, w:dict):
s = ''
if n > 99:
s += w[n//100] + w[100]
n = n % 100
if n > 20:
s += w[n//10*10]
n = n % 10
if n > 0:
s += w[n]
else:
s += w[n]
return s
def num_to_words2(n:int, w:dict):
s = ''
if n > 999:
p = 101
while n > 0:
if n%1000 != 0:
s = num_to_words(n%1000,w) + w[p] + s
n = n // 1000
p += 1
else:
s += num_to_words(n,w)
if len(s) == 0:
return 'Zero'
else:
return s
words = {
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 ',
101:'',
102:'Thousend ',
103:'Million ',
104:'Billion '
}
while True:
try:
n = int(input())
except ValueError:
continue
print(num_to_words2(n, words))
Comments
Leave a comment