Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Speech Module by Alkemic
FIRST_TEN = ["one", "two", "three", "four", "five", "six", "seven",
"eight", "nine"]
SECOND_TEN = ["ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
"sixteen", "seventeen", "eighteen", "nineteen"]
OTHER_TENS = ["twenty", "thirty", "forty", "fifty", "sixty", "seventy",
"eighty", "ninety"]
HUNDRED = "hundred"
def checkio(number):
number = str(number)[::-1] # reverse number, I want to iterate from lowest digits
parts = []
prev_digit = None
for i, digit in enumerate(number):
digit = int(digit)-1 # we will be substracking 1 every time, cus indexing goes from 0
if i == 0 and digit >= 0: # digit
parts.append(FIRST_TEN[digit])
elif i == 1 and digit == 0: # case 10-19
parts = []
parts.append(SECOND_TEN[prev_digit+1])
elif i == 1 and digit > 0: # case 20-90
parts.append(OTHER_TENS[digit-1])
elif i == 2 and digit >= 0: # hundrets
parts.append("%s %s" % (FIRST_TEN[digit], HUNDRED))
prev_digit = digit
return ' '.join(parts[::-1])
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
assert checkio(4) == 'four', "1st example"
assert checkio(133) == 'one hundred thirty three', "2nd example"
assert checkio(12) == 'twelve', "3rd example"
assert checkio(101) == 'one hundred one', "4th example"
assert checkio(212) == 'two hundred twelve', "5th example"
assert checkio(40) == 'forty', "6th example"
assert not checkio(212).endswith(' '), "Don't forget strip whitespaces at the end of string"
July 24, 2014