In: Computer Science
Design, implement, and fully test a Python3 function that converts a number to words (words_from_number(number: int)). It should expect to be passed a natural number (such as 12345) and return the corresponding words (i.e., “twelve thousand three hundred forty-five”). Since Python integers can grow arbitrarily large, your code should be flexible, handling at least 20 digits (realistically, it’s just as easy up to 30 digits). Spell everything correctly, and use correct punctuation (hyphens for forty-five and thirty-seven, no commas or plurals). You may only use built-in Python functions, not any modules or third-party libraries!
ones = {
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'}
tens = {
2: 'twenty', 3: 'thirty', 4: 'forty', 5: 'fifty', 6: 'sixty',
7: 'seventy', 8: 'eighty', 9: 'ninety'}
illions = {
1: 'thousand', 2: 'million', 3: 'billion', 4: 'trillion', 5: 'quadrillion',
6: 'quintillion', 7: 'sextillion', 8: 'septillion', 9: 'octillion',
10: 'nonillion', 11: 'decillion'}
def say_number(i):
"""
Convert an integer in to it's word representation.
say_number(i: integer) -> string
"""
if i < 0:
return _join('negative', _say_number_pos(-i))
if i == 0:
return 'zero'
return _say_number_pos(i)
def _say_number_pos(i):
if i < 20:
return ones[i]
if i < 100:
return _join(tens[i // 10], ones[i % 10])
if i < 1000:
return _divide(i, 100, 'hundred')
for illions_number, illions_name in illions.items():
if i < 1000**(illions_number + 1):
break
return _divide(i, 1000**illions_number, illions_name)
def _divide(dividend, divisor, magnitude):
return _join(
_say_number_pos(dividend // divisor),
magnitude,
_say_number_pos(dividend % divisor),
)
def _join(*args):
return ' '.join(filter(bool, args))
def output1(data):
output = say_number(data)
print(output)
i=int(input("Enter a number"))
output1(i)
Output: