Created
April 21, 2012 04:58
-
-
Save underhilllabs/2434111 to your computer and use it in GitHub Desktop.
Python function to translate a number to a word
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def numWords(num): | |
words = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", | |
"thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"] | |
iwords = ["", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"] | |
twords = ["","teen","twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"] | |
myStr = "" | |
huns = "" | |
# if over a thousand, first mod with 1000 to get next lower magnitude | |
if (num >= 1000): | |
tuns = num / 1000 | |
num = num % 1000 | |
myStr += iwords[tuns] + " thousand " | |
if (num >= 100): | |
# if over a hundred, find which hundred via integer division | |
huns = num / 100 | |
myStr += iwords[huns] + " hundred" | |
# now get next lowest magnitude via mod | |
num %= 100 | |
if num > 0: | |
myStr += " and " | |
if (num >= 20): | |
tens = num / 10 | |
num %= 10 | |
# add tens words | |
myStr += twords[tens] | |
if (num > 0): | |
myStr += "-"+words[num] | |
elif num > 0: | |
myStr += words[num] | |
return myStr |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment