If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used? Run this solution at repl.io here.
from math import floor
def num2words(n):
#a function that returns (positive) natural numbers less than 1000 as words
dictwords = {0: '', 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', 20: 'twenty', 30: 'thirty', 40: 'forty', \
50: 'fifty', 60: 'sixty', 70: 'seventy', 80: 'eighty', \
90: 'ninety'}
if n <= 20:
return dictwords[n]
elif n % 10 == 0 and n < 100:
return dictwords[n]
elif 20 < n < 100:
tens = (int(floor(n / 10))) * 10
units = int(str(n)[1])
return (dictwords[tens] + " " + dictwords[units])
elif n % 100 == 0 and n < 1000:
hundreds = int(str(n)[0])
return (dictwords[hundreds] + " hundred")
elif 100 <= n < 1000:
hundreds = int(str(n)[0])
#for numbers with zero tens
if int(str(n)[1]) == 0:
units = int(str(n)[2])
return (dictwords[hundreds] + " hundred and " + dictwords[units])
#for numbers with zero units or teens
elif int(str(n)[1:3]) % 10 == 0 or 10 < int(str(n)[1:3]) < 20:
tens = int(str(n)[1:3])
return (dictwords[hundreds] + " hundred and " + dictwords[tens])
else:
k = int(str(n)[1:3])
tens = (int(floor(k / 10))) * 10
units = int(str(n)[2])
return (dictwords[hundreds] + " hundred and " + dictwords[tens] + " " + dictwords[units])
elif n == 1000:
return "one thousand"
else:
return "You must enter a number less than a thousand"
#create word list of the first 1000 natural numbers
numlist = []
for n in range(1,1001):
numlist.append(num2words(n))
#count the letters in each word in numlist, excluding spaces
count = 0
for words in numlist:
for letters in words:
if letters != " ":
count += 1
print(count)