Last active
August 29, 2015 14:04
-
-
Save rohit-jamuar/f3dd85fc57119f9df16d to your computer and use it in GitHub Desktop.
Converts an integer (between 0 and 10,000) into its alphabetical form.
This file contains 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
#!/usr/bin/python | |
ONES = {1 : 'one', 2 : 'two', 3 : 'three', 4 : 'four', 5 : 'five', | |
6 : 'six', 7 : 'seven', 8 : 'eight', 9 : 'nine'} | |
ODDS = {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'} | |
def numeric_converter(num): | |
''' | |
A function that converts a (non-negative) integer into its | |
spoken-language form. | |
''' | |
if type(num) == int and 0 <= num < 10000 : | |
if num == 0: | |
return 'zero' | |
else: | |
fin = [] | |
if num / 1000: | |
fin.append(ONES[num/1000]) | |
fin.append('thousand') | |
num %= 1000 | |
if num / 100: | |
fin.append(ONES[num/100]) | |
fin.append('hundred') | |
num %= 100 | |
if num / 10: | |
if num/10 == 1: | |
fin.append(ODDS[num]) | |
num = 0 | |
else: | |
fin.append(TENS[num/10]) | |
num %= 10 | |
if num: | |
fin.append(ONES[num]) | |
return ' '.join(fin) | |
else: | |
return "The argument should be an integer \ | |
between 0 and 10,000!" | |
if __name__ == '__main__': | |
for i in [0, 10, 1023, 2004, 2020, 2200, 2202, 2220]: | |
print numeric_converter(i) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment