Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Speech Module by chrismartin
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):
"""
How I solved this:
1. Break up the input number into its digits. Add these to a list, so that
individial digits can be accessed easily.
Note that the list of digits is "backwards" - that is, the ones place is at
index 0, the tens place is at index 1, and the hundreds place is at index 2.
2. Starting with the hundreds place, check for existence of a digit in each
place, using if statements. If the digit exists, then look up its string
representation using the lists provided with this exercise. Add that string
to a list of output words.
Note that a 1 in the tens place must be handled differently than a 2
through 9 in the tens place, because of "ten, eleven", and all the "teen"s.
There is a special if statement to handle this.
3. Finally, join each element of the list of output words with spaces, and
return it as an output string.
"""
# Instantiate some variables. Here's an array of digits
digits = []
# Here's an array of words representing digits
words = []
# Populate digits with list of digits, starting with ones place
for digit in str(number):
digits.insert(0, int(digit))
# If input number has a hundreds place
if len(digits) == 3:
# Append string representation of hundreds place to words
words.append(FIRST_TEN[digits[2] - 1] + " hundred")
# If number has a tens place and it is between 2 and 9
if len(digits) > 1 and 2 <= digits[1] <= 9:
#Append string representation of tens place to words
words.append(OTHER_TENS[digits[1] - 2])
# If number has a tens place and it is 1
if len(digits) > 1 and digits[1] == 1:
# Append string representation of tens and ones place to words
words.append(SECOND_TEN[digits[0]])
# Else if number has a non-zero ones place
elif digits[0] != 0:
# Append string representation of ones place to words
words.append(FIRST_TEN[digits[0] - 1])
# Return string containing list of words separated by spaces
return " ".join(words)
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"
Aug. 27, 2014