Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Rule-based solution in Clear category for Speech Module by PositronicLlama
def evaluate(number):
"""
Return a string representation of the given integer.
Called recursively.
number: An integer less than a billion.
return: A list of lower case english words.
"""
RULES = [
StandardBase(1000000, 'million'),
StandardBase(1000, 'thousand'),
StandardBase(100, 'hundred'),
Tens(),
TeensAndDigits(),
]
result = []
remainder = number
while remainder:
for rule in RULES:
if rule.accept(remainder):
new_remainder, words = rule.apply(remainder)
result += words
break
if new_remainder == remainder:
print(number, remainder, result)
return [""]
remainder = new_remainder
return result
class StandardBase:
"""
A rule that handles hundreds, thousands, millions, etc.
"""
def __init__(self, base, name):
self.base = base
self.name = name
def accept(self, value):
return value >= self.base
def apply(self, value):
remainder = value % self.base
amount = value // self.base
return remainder, evaluate(amount) + [self.name]
class Tens:
"""
A rule that handles twenty, thirty, forty, etc...
"""
NAME = {
20: 'twenty',
30: 'thirty',
40: 'forty',
50: 'fifty',
60: 'sixty',
70: 'seventy',
80: 'eighty',
90: 'ninety',
}
def accept(self, value):
return value >= 20 and value < 100
def apply(self, value):
amount = 10 * (value // 10)
return value - amount, [Tens.NAME[amount]]
class TeensAndDigits:
"""
A rule that exactly handles all numbers less than 20.
"""
NAME = {
0: 'zero', 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five',
6: 'six', 7: 'seven', 8: 'eight', 9: 'nine', 10: 'ten', 11: 'eleven',
12: 'twelve', 13: 'thirteen', 14: 'fourteen', 15: 'fifteen',
16: 'sixteen', 17: 'seventeen', 18: 'eighteen', 19: 'nineteen'
}
def accept(self, value):
return value < 20
def apply(self, value):
return 0, [TeensAndDigits.NAME[value]]
def checkio(number):
"""
Return a string representation of the given integer.
number: A number in the range [0, 1000] (inclusive)
return: A space separated list of lower case english words.
"""
return " ".join(evaluate(number))
if __name__ == '__main__':
assert checkio(4) == 'four', "First"
assert checkio(133) == 'one hundred thirty three', "Second"
assert checkio(12)=='twelve', "Third"
assert checkio(101)=='one hundred one', "Fifth"
assert checkio(212)=="two hundred twelve", "Sixth"
assert checkio(40)=='forty', "Seventh, forty - it is correct"
print('All ok')
Dec. 6, 2012
Comments: