Sunday, July 12, 2020

Python - Number to Words

Program to convert Number to Words:

I am trying to teach Python to one of my old friend, and has given an assignment to convert numbers to words. So I tried doing it myself and It turned out to be fun.

I have used dictionary and recursive function :)

Code is readable so you may use logic in any language.


digitdict = {
  "0": "",
  "1": "One",
  "2": "Two",
  "3": "Three",
  "4": "Four",
  "5": "Five",
  "6": "Six",
  "7": "Seven",
  "8": "Eight",
  "9": "Nine",
}

tensdict = {
  "0": "",
  "1": "",
  "2": "Twety",
  "3": "Thirty",
  "4": "Fourty",
  "5": "Fifty",
  "6": "Sixty",
  "7": "Seventy",
  "8": "Eighty",
  "9": "Ninty",
}

exceptiondict = {
  "10": "Ten",
  "11": "Eleven",
  "12": "Twelve",
  "13": "Thirteen",
  "14": "Fourteen",
  "15": "Fifteen",
  "16": "Sixteen",
  "17": "Seventeen",
  "18": "Eighteen",
  "19": "Ninteen",
  "100": "Hundred",
}


def num2words(mydigit):

    wordstring = ""

    if mydigit in exceptiondict:
        return exceptiondict[mydigit]

    if len(mydigit) == 1:
        wordstring = digitdict[mydigit]

    if len(mydigit) == 2:
        wordstring = tensdict[mydigit[0]]
        wordstring = wordstring + " " + digitdict[mydigit[1]]

    if len(mydigit) == 3:
        if int(mydigit) > 99:
            wordstring = digitdict[mydigit[0]] + wordstring + " Hundred " + num2words(mydigit[1:])
        else:
            wordstring = num2words(mydigit[1:])
    if len(mydigit) == 4:
        wordstring = digitdict[mydigit[0]] + " Thousand " + num2words(mydigit[1:])

    if len(mydigit) == 5:
        wordstring = num2words(mydigit[0:2]) + " Thousand " + num2words(mydigit[2:5])

    if len(mydigit) == 6:
        wordstring = num2words(mydigit[0:3]) + " Thousand " + num2words(mydigit[3:6])

    if len(mydigit) > 6:
        wordstring = "you are a millionnaire, give me some..."
    return wordstring

#prompt = "type a number:"
#mydigit = input(prompt)
#print(num2words(mydigit))

while 1 == 1:
    prompt = "Type a number(0 to quit):"
    mydigit = input(prompt.strip())
    if mydigit.isnumeric():
        if int(mydigit) == 0:
            print("Bye")
            exit(0)
        else:
            print(num2words(mydigit))
    else:
        print("not a number...")


#for i in range (21341,21400,1):
#    print(num2words(str(i)))

No comments:

Post a Comment