If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.
If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used?
NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of "and" when writing out numbers is in compliance with British usage.
Iterate and calculate as instructed.
def solve(bound):
one_digit = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
_t = ['thir', 'four', 'fif', 'six', 'seven', 'eigh', 'nine']
teens = ['ten', 'eleven', 'twelve'] + [t+'teen' for t in _t]
ties = ['twenty'] + [t+'ty' for t in _t]
# 40 is 'forty'
ties[2] = 'forty'
def one_digit_letters(n):
return one_digit[n]
def two_digits_letters(n):
if n < 10:
return one_digit_letters(n)
elif n < 20:
return teens[n % 10]
else:
return ties[(n // 10) - 2] + (one_digit_letters(n % 10))
def three_digits_letters(n):
return one_digit_letters(n // 100) + 'hundred' + ('and' + two_digits_letters(n % 100) if n % 100 else '')
cnt = 0
for i in range(1, bound+1):
if len(str(i)) == 1:
cnt += len(one_digit_letters(i))
elif len(str(i)) == 2:
cnt += len(two_digits_letters(i))
elif len(str(i)) == 3:
cnt += len(three_digits_letters(i))
elif len(str(i)) == 4:
cnt += len('onethousand')
return cnt
solve(5)
solve(1000)