Problem #17 is the first of many Project Euler problems that are very easy with certain libraries, but are painful to implement otherwise. Here is the question:
Project Euler Problem 17: Number letter counts
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.
While this problem may sound simple, it would be quite annoying to implement. There are many, many cases that you have to consider, such as the way how the numbers 11-19 are converted to English differently than the numbers 21-29 or 31-39. As a result, this would be a very nasty problem to solve legitimately without external tools. Luckily, computer scientists have access to a massive variety of libraries that are built just to solve problems like this.
Solution #1: Library Approach
As it turns out, the Python library “inflect.py” comes with a number of functions that are made exactly for the purpose of converting numbers to English. Because implementing this problem would be nasty (plus I’m lazy), it is much easier to just import a library that can solve it for us. Here is a solution that utilizes the inflect Python library:
'''
Author: Walker Kroubalkian
Library Approach to Project Euler Problem #17
'''
import inflect
import time
def countLetters(myString):
total = 0
for c in myString:
if "a"<=c<="z":
total+=1
return total
def projectEulerProblemSeventeen(n):
total = 0
i = inflect.engine()
for x in range(1,(n+1)):
total+=countLetters(i.number_to_words(x))
return total
start = time.time()
print projectEulerProblemSeventeen(1000)
print ("--- %s seconds ---" % (time.time()-start))
'''
Prints
21124
--- 0.0325779914856 seconds ---
for input of n=1000
'''
And without doing much work at all, we are done.
Thanks for reading!