Integer to English Words in Python

PythonServer Side ProgrammingProgramming

Suppose we have a number. The number can be anything in between 0 to 231 – 1. We have to convert the number into words. So if the number is like 512, then the result will be Five hundred twelve.

To solve this, we will follow these steps −

  • Define some lists like less_than_20, this will hold all words from one to nineteen

  • Another array like tens to hold tens, twenty, thirty and so on up to ninety

  • Another array for thousands, to hold thousand, million and billion

  • Define one function called helper(), this will take n

  • if n is 0, then return blank string

  • otherwise when n < 20, then return less_than_20[n] + blank space

  • otherwise when n < 100, then return tens[n/10] + blank space + helper(n mod 10)

  • otherwise return less_than_20[n/100] + “Hundred” + helper(n mod 100)

  • From the main method, do the following

  • if num is 0, then return “Zero”

  • ans := empty string, i := 0

  • while num > 0

    • if num mod 1000 is not 0, then

      • ans := helper(num mod 1000) + thousands[i] + blank space + ans

      • num := num / 1000

  • return ans

Example

Let us see the following implementation to get a better understanding −

 Live Demo

class Solution(object):
   less_than_20 = ["", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen",
"Nineteen"]
   tens = ["","Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"]
   thousands = ["", "Thousand", "Million", "Billion"]
   def numberToWords(self, num):
      if num == 0:
         return "Zero"
      ans = ""
      i = 0
      while num > 0:
         if num % 1000 != 0:
            ans = self.helper(num % 1000) + Solution.thousands[i] + " " + ans
         i += 1
         num //= 1000
      return ans.strip()
   def helper(self, n):
      if n == 0:
         return ""
      elif n < 20:
         return Solution.less_than_20[n] + " "
      elif n < 100:
         return Solution.tens[n//10] + " " + self.helper(n % 10)
      else:
         return Solution.less_than_20[n // 100] + " Hundred " + self.helper(n % 100)

ob = Solution()
print(ob.numberToWords(512))
print(ob.numberToWords(7835271))

Input

512
7835271

Output

Five Hundred Twelve
Seven Million Eight Hundred Thirty Five Thousand Two Hundred Seventy One
raja
Published on 27-May-2020 09:09:10
Advertisements