Answer to Question #201369 in Python for praveen

Question #201369

Number to English Words

Write a program to convert a non-negative integer

N to its English words representation.Input

The input will be a single line containing an integer

N. Note: The input number will not be greater than 1010.OutputN. Note: Don't use any libraries function tools


The output should be a single line containing the representation of the English words of number

N. See the sample input and output for the English words of numbers in places.Explanation

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






1
Expert's answer
2021-05-31T16:36:25-0400
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))

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS