def single_digit_integer_to_spoken_language(n): if n == 0: return "" assert(n > 0 and n < 10) return {1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine'}[n] def double_digit_integer_to_spoken_language(n): assert(n > 9 and n < 100) try: return { 10: 'ten', 11: 'eleven', 12: 'twelve', 13: 'thirteen', 14: 'fourteen', 15: 'fifteen', 16: 'sixteen', 17: 'seventeen', 18: 'eighteen', 19: 'nineteen'}[n] except KeyError: pass a, b = str(n) a = {2: 'twenty', 3: 'thirty', 4: 'forty', 5: 'fifty', 6: 'sixty', 7: 'seventy', 8: 'eighty', 9: 'ninety'}[int(a)] b = integer_to_spoken_language(int(b)) return a + '-' + b def triple_digit_integer_to_spoken_language(n): a, b = str(n)[0], str(n)[1:] a = single_digit_integer_to_spoken_language(int(a)) b = integer_to_spoken_language(int(b)) if not b: return a + " hundred" return a + " hundred and " + b def four_digit_integer_to_spoken_language(n): a, b = str(n)[0], str(n)[1:] a = single_digit_integer_to_spoken_language(int(a)) b = integer_to_spoken_language(int(b)) return a + " thousand " + b def integer_to_spoken_language(n): length = len(str(n)) if length == 1: return single_digit_integer_to_spoken_language(n) elif length == 2: return double_digit_integer_to_spoken_language(n) elif length == 3: return triple_digit_integer_to_spoken_language(n) elif length == 4: return four_digit_integer_to_spoken_language(n) else: raise Exception("Length not supported.") assert(integer_to_spoken_language(5) == 'five') assert(integer_to_spoken_language(19) == 'nineteen') assert(integer_to_spoken_language(21) == 'twenty-one') assert(integer_to_spoken_language(210) == 'two hundred and ten') assert(integer_to_spoken_language(3000) == 'three thousand ') assert(integer_to_spoken_language(8333) == 'eight thousand three hundred and thirty-three') def euler_017(): s = "".join([integer_to_spoken_language(i) for i in range(1, 1001)]) s = s.replace(" ", "").replace("-", "") return len(s) assert(euler_017() == 21124) print("e017.py: {}".format(euler_017()))